Thursday, April 10, 2008

Object Introspection in Flex

Object Introspection can be a handy tool to learn about large objects without documentation or to list all public properties, methods etc at runtime

import flash.utils.*; and use the method describeType() , passing it target object to be inspected. The result may be parsed using E4X API

If you call describeType(this) , non-static members returned

If you call describeType(getDefinitionByName("MyClass")) , static members returned

An example from Adobe Flex 3 reference to use it for a Button. Assume a Button with id button1:

import flash.utils.*;

pubic function inspector():void{
//get E4X description
var classInfo:XML = describeType(button1);

//class name
var className:String = classInfo.@name.toString();

//variables and their types
var classVarStr:String="";

for each(var v:XML in classInfo..variable){
classVarStr+= "Variable "+ v.@name + "=" + button1[v.@name] + "("+v.@type+")\n";
}

//properties, type and value
var classPropStr:String="";

for each(var a:XML in classInfo..accessor){

//no need to get value if write only
if(a.@access == 'writeOnly'){
classPropStr+="Property "+ a.@name + "(" + a.@type + ")\n";
}else{
classPropStr+="Property "+ a.@name + "=" +button1[a.@name] + "(" + a.@type + ")\n";
}
}

//methods
var classMethodStr:String="";

for each(var m:XML in classInfo..method){
classMethodStr += "Method " + m.@name + "():" + m.@returnType + "\n";
}

}