Actionscript: Determining if a Class object is a superclass or superinterface of another Class

Anyone who uses actionscript reflection in non-trivial cases will eventually run into this problem: The is operator only works on instances. For example:

This behavior is expected, but not very useful. Since cls is actually an instance of the Class class, we are actually checking whether the Class class inherits from each of those 5 things. Since Class only extends Object, that’s the only one that’s true.

What happens if you only have a Class object and you need to check if it’s the subclass of another Class?

Something equivalent to isAssignableFrom in Java would be excellent. Unfortunately, there is no simple solution built-in. There are, however, three solutions that I have come up with:

1. Make an instance

This is the most direct method but it has some limitations:

  • Class a must provide a no-argument constructor.
  • You must deal with the overhead of instantiating a new object.
  • You can’t check if an interface extends another interface. Since you can’t instantiate an interface, a must be a regular class.
  • Class a must be constructable. Some classes like DisplayObject and Class do not allow instantiation.

2. Use getQualifiedSuperclassName()

This method can’t handle interfaces at all. Since getQualifiedSuperclassName only walks the class inheritance chain, it will never touch the interfaces of clsA. If clsB is an interface, this method will always return false. If clsA is an interface, this method will throw an error since getQualifiedSuperclassName returns null for interfaces.

3. Use describeType()

This method eliminates the problems of the first 2 method, but at the cost of performance. describeType is an expensive method. It returns an XML document describing every aspect of a given object. If you are only running this check a few times, this cost is negligible, but for many calls it can add up quickly. describeType is also stupid; 2 successive requests to describe the same object will cause all the XML to be generated twice. If you know that you will be checking the same types many times, I strongly urge you to consider caching the description XML.

Performance Comparison

I set up a test with 25 random classes from the Flex API and used each method to compare every class to every other class (including themselves). I used the Flash Builder profiler to record time in each method.

Method # of test runs Cumulative time Average cumulative time
Create an instance 1625 381 ms 0.23 ms
Use getQualifiedSuperclassName 1625 181 ms 0.11 ms
Use describeType 325 11391 ms(11027 ms of this spent running describeType) 35.05 ms
Use describeType with XML cached after first request 325 717 ms 2.2 ms


Leave a Reply

Your email address will not be published. Required fields are marked *