AS3 - Can I know if a class implements an interface (or is a subclass of another class)?

独自空忆成欢 提交于 2019-12-23 07:56:18

问题


With this code

function someFunction(classParam:Class):Boolean
{
    // how to know if classParam implements some interface?
}

i.e. Comparing classParam with IEventDispatcher interface:

someFunction(EventDispatcher) // returns true
someFunction(Object) // returns false

I know it can't be done with is operator. But, is there a way to do it? Is there a way to know if a class implements some interface? (or is a subclass of another class?)

Possible solutions:

A. Creating an object of classParam and using that object to compare using is operator.

function someFunction(classParam:Class):Boolean
{
    return (new classParam()) is IEventDispatcher
}

B. Using describeType()

function someFunction(classParam:Class):Boolean
{
    var xml:XML = describeType(classParam)
    // found "implementsInterface" value in xml and compare to IEventDispatcher
}

There is a way that DOES NOT USE describeType or creates a new operator?


回答1:


I don't see any way to achieve what you're trying to do except by using describeType.
It has been created for this purpose, why don't you want to use it?

Edit:
It actually only takes 2 lines to do this :

var classDescription:XML = describeType(classParam);
return (classDescription.factory.implementsInterface.(@type == getQualifiedClassName(IEventDispatcher)).length() != 0);

...or just in one, if it's what bothers you:

return (describeType(classParam).factory.implementsInterface.(@type == getQualifiedClassName(IEventDispatcher)).length() != 0);



回答2:


Maybe the code samples in this article will provide an answer: Runtime Checks for Abstract Classes and Methods in ActionScript 3.0




回答3:


Adding to 'Zed-K' response. I ended up not needing the .factory part. Here is a example of a test that checks that the class is utilizing and interface. '_instance' is the class under test.

[Test]
public function testInstanceShouldBeIUser():void
{
    var classDescription:XML = describeType( _instance );
    var type:String = getQualifiedClassName(IUser);
    var xmlList:XMLList = classDescription.implementsInterface.(@type == type);
    assertTrue("expected IUser", xmlList.length() != 0 );
}



回答4:


Probably not. Btw, there is also describeTypeJSON, witch is about 5x faster than describeType.



来源:https://stackoverflow.com/questions/2518180/as3-can-i-know-if-a-class-implements-an-interface-or-is-a-subclass-of-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!