我们有Class对象(引用Class的对象),因此您可以从该Class对象创建对象:
var classObject:Class = package.to.class.AClass;
var objectFromClass:AClass = new classObject();
现在,我想知道classObject
引用了哪个对象。例如:
function Creator(classObject:Class):AClass
{
// here I want to know what class is referenced by classObject
return new classObject();
}
var classObject:Class = package.to.class.AClass;
var objectFromClass:AClass = Creator(classObject);
这有效,但如果我传递一个不引用AClass
的Class对象怎么办?我想知道这是否发生并对此有所了解。
---编辑---
搜索我发现了这个功能
flash.utils.getQualifiedClassName(值:*):字符串 此函数返回类的名称,例如:
var name:String = '';
// name = ''
name = flash.utils.getQualifiedClassName(package.to.class.AClass);
// name = 'AClass'
name = ''
// name = ''
var anInstance:AClass = new AClass();
name = flash.utils.getQualifiedClassName(anInstance);
// name = 'AClass'
所以,我所要做的就是比较该函数的结果:
function Creator(classObject:Class):AClass
{
var anInstance:AClass = new AClass();
var className:String = flash.utils.getQualifiedClassName(anInstance);
var classObjectName:String = flash.utils.getQualifiedClassName(classObject);
// here className and classObjectName are 'AClass' :)
if (className != classObjectName)
throw new Error('The classes are different');
return new classObject();
}
var classObject:Class = package.to.class.AClass;
var objectFromClass:AClass = Creator(classObject);
---编辑2 ---
另一种方法是使用Object类的构造函数属性:
function Creator(classObject:Class):AClass
{
var tempInstance:AClass = new AClass();
var tempClassObject:Class = Object(tempInstance).constructor;
if (classObject != tempClassObject)
throw new Error('The classes are different');
return new classObject();
}
答案 0 :(得分:1)
我发现完成此任务的最简单(不知道是否是最快)的方法是在下一个示例中:
function Creator(classObject:Class):AClass
{
var anInstance:Object = new classObject() as AClass;
if (anInstance == null)
throw new Error('The classes are different');
return new classObject(); // or return anInstance as AClass;
}
如果AClass
是一个接口,这也有效。