Friday, March 21, 2008

How to get the Class of any Object in ActionScript 3 and Flex

Here's a small trick I recently learned. It's very helpful in some situations.

If you need to know the class of a random object:

private function getObjectClass(obj:*):Class {
var className:String = getQualifiedClassName(obj);
var classOfObj:Class = ApplicationDomain.currentDomain.getDefinition(className) as Class;

return classOfObj;
}


And creating another instance of that object is just a step forward:

private function newInstanceOf(obj:*):Object {
var objectClass:Class = getObjectClass(obj);

if(objectClass) {
return new objectClass();
}

return null;
}



Notice: this last trick will work only if you know for sure that the constructor for those objects don't need any parameters (either have none defined, or all have default values). If you're not sure, consider wrapping the code inside a try-catch block. If, however, you know that the constructor will require arguments, please tell me how you solved this, I'm still thinking about an elegant solution.

Here's a full working example written for Flex3.

Hope it helps.

No comments: