AS3: call a static class method - class and method names are strings

核能气质少年 提交于 2019-12-12 08:32:56

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2045548/as3-call-a-static-class-method-class-and-method-names-are-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!