apache-flexfunctionflex4callbackclosures

Flex: passing in function and checking parameters


I am passing in a function to another function which works well. Let's say function "inner" is being passed to function "outer". My problem is that I want function "outer" to be able to check if there are any parameters in function "inner" and their type. I am using the inner function as a callback so it is important that it has one parameter of a specific type. I would like to catch any problems as early as possible so want the "outer" function to check this.

How can I check a function's parameters? Is this possible in Flex?

Thanks


Solution

  • at compile time

    Actually it's possible to have compile time checking. It just depends how big a leap you're willing to make. For this to work you will have to write your code in Haxe instead of ActionScript and have it targeting the Flash platform when compiling. There's a good read on Haxe function types on Devboy's blog.

    at runtime

    If you don't want to go that far, here's how to do it in AS: you'll have to use the describeType() function. Suppose you have a test class like this one:

    public class TestClass {    
        public function test(s:String):void {}
    }
    

    We can now get information about its functions by writing:

    var info:XML = describeType(TestClass);
    

    Somewhere in this XML object there will be a node that looks like this:

    <method name="test" declaredBy="net.riastar.test::TestClass" returnType="void">
      <parameter index="1" type="String" optional="false"/>
    </method>
    

    There it is! All the information you need to do your checking. But there's one big caveat in this approach: the describeType method is not very efficient. If you have to do this a lot, it will slow down your application. You could use a caching strategy to avoid this though. Or have a look at the as3-commons-reflect project, it will take care of the caching for you.