views:

653

answers:

2

Hi,

I have an ugly problem. I have two string variables (className and staticMethod) store the name of a class and it's static method I have to call:

package {
 import flash.display.Sprite;
 import flash.utils.getDefinitionByName;
 import flash.utils.getQualifiedClassName;

 public class ClassPlay extends Sprite {

  public function ClassPlay() {
   new Foo();
   var className:String = 'Foo';
   var staticMethod:String = 'bar';
   var classClass:Class = getDefinitionByName(className) as Class;
   try {
    classClass[staticMethod]();
   } catch (e:Error) {}
  }
 }
}

This is the subject class:

package {
 public class Foo {
  public static function bar():void {trace('Foo.bar() was called.');}
 }
}

It works just perfectly. The problem when you comment out this (9th) line:

// new Foo();

Without this line it exits with an exception:

ReferenceError: Error #1065: Variable Foo is not defined.

How could I do this without that instantiation? If that is impossible, is there a way to instantiate the class from the string variable? Or if it's still a bad practice, how would you do that? (I have to work with those two unknown string variable.)

Thanks in advance.

+6  A: 

The reason is that the compiler will strip out unnecessary classes - if you don't have an explicit reference to the class Foo somewhere, it won't be present in your final application.

You could the reference elsewhere and still force it to be loaded - for example, a static array of references to the classes.

Anon.
This is also a common problem when using dependency injection in as3. For other options, check out http://www.springactionscript.org/docs/reference/html/Class-inclusion.html (note: the site is down now, but should be back eventually).
RJ Regenold
Great thanks for the link;) Site is up again.
itarato
A: 

It should work if you just throw in a trace(classClass) - that should give you the reference you need, if I remember this stuff correctly.

Myk
I don't think you even need to go that far. I belive if you just put the class name in your code (other than in a import statement) it'll get included. The complier is pretty dumb. for example:Sprite;MyClass;
Tyler Egeto
No, it's not working. Error was thrown when classClass was initializing.
itarato