AS3:调用静态类方法——类名和方法名都是字符串 [英] AS3: call a static class method - class and method names are strings
问题描述
我有一个丑陋的问题.我有两个字符串变量(className 和 staticMethod)存储一个类的名称,它是我必须调用的静态方法:
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.)
提前致谢.
推荐答案
原因是编译器会剔除不必要的类 - 如果你在某处没有显式引用 Foo
类,它将不会出现在您的最终申请中.
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.
这篇关于AS3:调用静态类方法——类名和方法名都是字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!