开发者

How can I determine a Class's superclass at runtime?

In Actionscript 3, if I'm given a Class object, is there any way to determine if that class extends from another given class? I don't want to instantiate the class to check it with the is keyword, though.

More specifically, I'm trying to make this function work:

public function validateClass(classObj:Class):EngineObject{
    if(classObj extends EngineObject){
        return new classObj();
    } else {开发者_如何学编程
        throw new Error("Given class is not a subclass of EngineObject!");
    }
}

Edit: forgot that in is reserved in AS3


Have a look at flash.utils.getQualifiedSuperclassName() and flash.utils.getQualifiedClassName()

Your function could look like this.

import flash.utils.getQualifiedSuperclassName;
import flash.utils.getQualifiedClassName;

public function validateClass(cl:Class):EngineObject{
    if(getQualifiedSuperclassName(cl) == getQualifiedClassName(EngineObject) ){
        return new cl();
    } else {
        throw new Error("Given class is not a subclass of EngineObject!");
    }
}

But this will only work for a single iteration depth.

You could do this for each iteration step until you are on object level. Here a complete approach.

public function validateClass(cl:Class):EngineObject
{
    if ( getQualifiedSuperclassName(cl) == getQualifiedClassName(EngineObject) )
    {
        return new cl();
    }

    var sup:Class = getDefinitionByName(getQualifiedSuperclassName(cl)) as Class;
    if ( sup == null || getQualifiedSuperclassName(sup) == getQualifiedClassName(Object) )
    {
        throw new Error("Given class is not a subclass of EngineObject!");
    }

    return validateClass(sup);
}


function validateClass($class:Class):EngineObject {
    var qn:String = getQualifiedClassName($class);
    var en:String = getQualifiedClassName(EngineObject);
    while(qn != "Object") {
        if(qn == en) return new $class();
        qn = getQualifiedSuperclassName(getDefinitionByName(qn));
    }
    throw new Error("Given class is not a subclass of EngineObject!");
}

The idea here is the get the qualified name of the superclass and compare it to the qualified name of EngineObject. If this doesn't match, the superclass is set as the new class name, and the loop runs again. When the qualified superclass name is Object you know there are no more ancestors to check.


You could use describeType to figure out all of the classes any given type extends from, and a lot of other interesting stuff.

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/package.html#describeType()

describeType returns an XML with pretty much everything you'd want to know about a class. All you need to do is loop through all the elements called extendsClass, and compare their attribute type to a classname of your choice. To figure out the classname, just use getQualifiedClassName on the type you're comparing to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜