mardi 8 septembre 2015

Call function by variable string name and variable parameter

Scenario: I have a list of functions, example :

function1(int a, int b)
function2(String a)
function3(String a, String a)
...

I need to be able to select and call a function by a string while also having different parameters.

String functionName = "function1" 

or

String functionName = "function2"

and then callFunction(functionName) - (somehow adding parameters too)

I can do this with using:

if(functionName == "function1"){
function1(int a, int b);
}else if(functionName == "function2"){
function2(String a)
}...

But this doesn't seem efficient when I have a long list of functions.

I have tried using reflection:

String methodName = "thisMethod";
        Method newMethod = null;
        try {
            newMethod = FormActions.class.getMethod(methodName, String.class);
        } catch (e) {}
        try {
            newMethod.invoke(this, "THIS IS A STRING");
        } catch (e) {}

which is good because I can call:

public void thisMethod(String text ){
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }

however if methodName was set to "otherMethod" which takes a int = otherMethod(int a)

Then this would no longer work.

Is there a good way to doing this or should I use the first if-else/switch method.





Aucun commentaire:

Enregistrer un commentaire