views:

109

answers:

2

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?

A: 

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

M.A. Hanin
A: 

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);
Zed-K
What bothers me is the speed of `describeType`. Isn't it slow?
unkiwii
It depends of how much you are using it, but yes, it's pretty slow. Problem is I don't think there's another way to achieve this. This article may interest you, the author made a benchmark and found out that a describeType on UIComponent takes 5ms on his computer: http://faindu.wordpress.com/2010/02/01/actionscript-flex-dependency-injection-performance/
Zed-K
So creating the object will take less time? I will run a benchmark on that to see it.
unkiwii
Here is the benchmark: http://dl.dropbox.com/u/2283327/stackoverflow/describeTypeBenchmark/describeTypeBenchmark.html
unkiwii
Thanks for the benchmark, results are very interesting. And it proves that describeType is indeed _really_ slow =/
Zed-K