如果类名称为字符串,是否可以构造该类的实例?例如:
var className:String = "MyClass";
var obj:* = new getClass(className)();
答案 0 :(得分:2)
有可能。你必须使用getDefinitionByName(name:String):Object
确保您引用的类在swf文件中可用
var ClassReference:Class = getDefinitionByName("flash.display.Sprite") as Class;
var instance:Object = new ClassReference();
答案 1 :(得分:2)
虽然给定的答案是正确的,但如果您使用的是应用程序域,则可能无效。
要考虑应用程序域,请使用以下方法:
public static function forName(name:String, applicationDomain:ApplicationDomain = null):Class {
applicationDomain ||= ApplicationDomain.currentDomain;
var result:Class;
while (!applicationDomain.hasDefinition(name)) {
if (applicationDomain.parentDomain) {
applicationDomain = applicationDomain.parentDomain;
} else {
break;
}
}
try {
result = applicationDomain.getDefinition(name) as Class;
} catch (e:ReferenceError) {
throw new ClassNotFoundError("A class with the name '" + name + "' could not be found.");
}
return result;
}
var myClass:Class = forName(className);
var instance:Object = new myClass();
中提供了此方法和许多其他实用程序
答案 2 :(得分:1)
试试这个:
import flash.utils.getDefinitionByName;
var className:String = "MyClass";
var obj:Object = new (getDefinitionByName(className) as Class)();
答案 3 :(得分:0)
是的!
var myClass:Class = getDefinitionByName(className) as Class;
var instance:Object = new myClass();