PDA

View Full Version : Checking a Class inheritance without instantiating


jaga
04-01-2008, 02:18 PM
This is a subtle problem I've run in to, where I want to pass a Class reference and check if it inherits from another class type, without instantiating it

Here is what I mean, in semi-pseudo code:

function myFunction(myClass:Class) {
if (myClass is a DisplayObject or inherits from it) {
}
}


Now I know that I can do something like:

var a:myClass = new myClass();
if (a is DisplayObject) {
}


but that's not only ugly, but a complete waste of resources and also a possible run-time error..

Any ideas?

jaga
04-01-2008, 03:29 PM
Well I solved the issue, if anyone's interested..


// Use..
var myClass:Class = Sprite;
if (extendsClass(myClass, DisplayObject)) {
//
}

function extendsClass(inputClass:Class, compareClass:Class):Boolean {
var inheritanceData:XML = describeType(inputClass);
var extendsList:XMLList = inheritanceData..factory.child("extendsClass").@*;
for each (var extended:String in extendsList) {
var classDef:Object = getDefinitionByName(extended);
if (classDef == compareClass) {
return true;
}
}
return false;
}


Is this the most efficient way to do this though?

creynders
04-01-2008, 03:56 PM
Nice, this can be very useful...

wvxvw
04-01-2008, 04:06 PM
It seems to be the good solution...
I just found something weird trying to do smth similar:
var myClass:Class = Sprite;
if (extendsClass(myClass.prototype, Object)) {
trace('true');
}
function extendsClass(a:Object, b:Class):Boolean {
if(b.isPrototypeOf(a)){
return true;
}
return false;
} It doesn't really matter what will you pass as the first argument, but if the second argument is Object the Flash IDE will collaps %)

jaga
04-01-2008, 07:09 PM
I.. will take your word for it hehe, I dont need yet another reason to crash the flash IDE..

isPrototypeOf only works for checking if an instance is a direct descendant of an object, right? I can't actually get it to work properly *scratches head*