views:

123

answers:

1

We have the Class object (an object that reference a Class) so you can create objects from that Class object:

var classObject:Class = package.to.class.AClass;
var objectFromClass:AClass = new classObject();

Now, I want to know what object is referenced by classObject. For example:

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);

This works, but what if I pass a Class object that do not reference to AClass? I want to know if this happends and make somthing about it.

--- EDIT ---

Searching I found this function

flash.utils.getQualifiedClassName(value:*):String This function returns the name of the class, for example:

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'

So, all I have to do is to compare the results of that function:

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);

--- EDIT 2 ---

Another method is to use the constructor property of the Object class:

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();
}
+1  A: 

I found that the most simplest (not know if it's the fastest) way to accomplish this task is in the next example:

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;
}

This also works if AClass is an Interface.

unkiwii
Instead of casting to AClass and checking if it is null, why not use the 'is' operator?
Turambar