AS3:调用类的静态方法 - 类和方法名是字符串法名、字符串、静态、方法

2023-09-08 13:30:32 作者:俄╮冷血不需要理由

我有一个丑陋的问题。我有两个字符串变量(类名和静态方法)存储类的名称和它的静态方法我必须调用:

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) {}
  }
 }
}

这是主题类:

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

它的工作原理只是完美。当你注释掉这个(9)线路问题:

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.)

在此先感谢。

推荐答案

原因是,编译器将去掉不必要的类 - 如果你没有一个明确提及类的地方,它不会是present在最终的应用程序。

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.