0

如果类名被称为字符串,是否可以构造该类的实例?例子:

var className:String = "MyClass";
var obj:* = new getClass(className)();
4

4 回答 4

2

有可能的。您必须使用getDefinitionByName(name:String):Object 确保您引用的类在 swf 文件中可用

 var ClassReference:Class = getDefinitionByName("flash.display.Sprite") as Class;
 var instance:Object = new ClassReference();
于 2013-06-05T11:23:49.127 回答
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();

AS3Commons Lang库中提供了此方法和许多其他实用程序

于 2013-06-05T11:34:17.950 回答
1

试试这个:

import flash.utils.getDefinitionByName;
var className:String = "MyClass";
var obj:Object = new (getDefinitionByName(className) as Class)();
于 2013-06-05T11:24:31.343 回答
0

是的!

var myClass:Class = getDefinitionByName(className) as Class;
var instance:Object = new myClass();
于 2013-06-05T11:24:54.937 回答