How to find out which class the class object is referring to?

We have a class object (an object that refers to 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 which object is being referenced 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 in an object of a class that is not referenced AClass

? I want to know if this will happen and do something about it.

--- EDIT ---

Search I found this function

flash.utils.getQualifiedClassName (value: *): String This function returns the class name, 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 compare the results of this 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();
}

      

+2


source to share


1 answer


I found that the easiest (don't know if it's the fastest) way to accomplish this task is in the following 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 it AClass

is an interface.

+1


source







All Articles