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

时间:2013-06-05 11:14:48

标签: actionscript-3 flash flex dynamic actionscript

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

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

4 个答案:

答案 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();

AS3Commons Lang

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

答案 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();