简体   繁体   中英

Given the package, class, function(s), and parameters in Strings, how can I dynamically invoke a function in AS3?

I need to send requests between two separate .swf s, A and B . I have an interface , IRequest with the following methods:

public interface IRequest {
    function get packagePath():String;
    function get className():String;
    function get functions():Vector.<String>;
    function get parameters():Array;
    function execute():void;
}

I implement it in a class, Request . One can create a new request as follows: RequestManager.addToQueue(new Request("com.myPackage", "MyClass", "instance.method1.method2", "parameter"));

This creates a new Request with a supplied package , class -name, list of functions and parameters .

Things become complicated with a chain of function -calls and deciding if a function is actually a function or property ( public function getMyThing():Object vs public function get myThing():Object ).

For example, things are simple enough if the desired Request is new Request("com.myPackage", "MyClass", "getInstance", "");

Invoking that method is as simple as:

var theClass:Class = getDefinitionByName(packagePath + "." + className) as Class;
var theInstance:Object = theClass[functions[0]](); // Invokes com.myPackage.MyClass.getInstance()

However, this won't work if getInstance is a property / getter . Also, if there are numerous method calls, I'm not sure how to invoke the chain in one call. For example:

var theClass:Class = getDefinitionByName(packagePath + "." + className) as Class;
var object = theClass[functions[0]]()[functions[1]()[functions[2](); // Invokes com.myPackage.MyClass.firstMethod.secondMethod.thirdMethod()

However, I need to do this dynamically, and I don't see an easy way of dynamically chaining those [ , ] .

If anyone knows a nice way for me to be able to invoke methods from a String , that's essentially what I want to do.

"com.myPackage.MyClass.firstMethod.secondMethod.thirdMethod()", parameters

Thanks for the help,

I think doing a check whether that argument actually holds a function before invoking it would help.

var theClass:Class = getDefinitionByName(packagePath + "." + className) as Class;

if(theClass[functions[0]] is Function){
    var theInstance:Object = theClass[functions[0]](); // Invokes com.myPackage.MyClass.getInstance()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM