Frerich Raabe
Frerich Raabe

Reputation: 94409

How can I introspect the signature of a Flex function?

Given a function like

function printAndAdd( s: String, a: int, b: int ) {
  // ...
}

Is there any way to enumerate the arguments of the function (their names as well as their types) at runtime? Something like

for ( var arg: ArgumentDescriptor in printAndAdd ) {
    // arg.type yields the class object of the argument, i.e. 'String' or 'int'.
    // arg.name yields the name of the argument, i.e. 's' or 'a'
}

I have a list of event handlers which have different signatures, and I get the name of the event handler to call as well as an Array of objects. I could just apply() the array to the function, but I'd like to do some error checking first to give better error messages.

Upvotes: 0

Views: 94

Answers (1)

RIAstar
RIAstar

Reputation: 11912

You can use describeType() to find the information you seek. However for this to work the function must be public. Private methods will not be introspected by describeType().

Assuming printAndAdd is a method of MyClass, you can do this:

var metadata:XML = describeType(MyClass);
//find all the 'parameter' nodes of any method called 'printAndAdd'
var params:XMLList = metadata..method.(@name == "printAndAdd").parameter;

for each (var param:XML in params) {
    var index:int = param.@index;
    var type:String = param.@type;
    var optional:Boolean = param.@optional == "true";
}

One thing you will not be able to find, is the name of the paramater, but I suppose its index may suffice for your goal.

If you need more powerful reflection than this, take a look at the as3commons reflect library.

Upvotes: 2

Related Questions