moock.org is supported in part by


June 27, 2007

checking if one class inherits from another

in ActionScript 3.0 you can list all of the ancestors of a class like this:

var theClass:Class = Sprite;
var superName:String;
while (superName != "Object") {
  // Retrieve the name of theClass's superclass
  superName = getQualifiedSuperclassName(theClass);
  trace(superName);
  // Retrieve a reference to theClass's superclass
  theClass = Class(getDefinitionByName(superName));
}

Output:

flash.display::DisplayObjectContainer
flash.display::InteractiveObject
flash.display::DisplayObject
flash.events::EventDispatcher
Object

here's a generalized function that uses the same basic technique to check whether one class inherits from another:

import flash.utils.*;
  public function inheritsFrom (descendant:Class, 
                                ancestor:Class):Boolean { 
  var superName:String;
  var ancestorClassName:String = getQualifiedClassName(ancestor);
  while (superName != "Object") {
    superName = getQualifiedSuperclassName(descendant);
    if (superName == ancestorClassName) {
      return true;
    }
    descendant = Class(getDefinitionByName(superName));
  }
  return false;
}

Usage:

trace("Does Sprite inherit from DisplayObject?");
// Displays: yes
trace(inheritsFrom(Sprite, DisplayObject) ? "yes" : "no");
Posted by moock at June 27, 2007 05:14 PM