Java/Android calls methods from the string WITH Value

Java/Android calls methods from the string WITH Value … here is a solution to the problem.

Java/Android calls methods from the string WITH Value

Let’s say I have a method I want to call, and it has a string parameter

To call, I’d do something like this:
My function (string value);

Now, if I have a string with the value ‘myFunction’, how would I make the same call, but dynamically…

Kind of like

method = [convert "myFunction" string to method];
method.invoke(stringValue);

I’m currently trying something similar

java.lang.reflect.Method method;

method = Class.forName("com.blah.MyActivity").getMethod('myFunction',String.class);
method.invoke (stringValue);

But there is an error
Illegal parameter exception
The message expects a recipient of type com.blah.MyActivity, but results in java.lang.String

Solution

Description:

method.invoke (stringValue);

The object that needs to call the method.

So, if you try something like this:

method = Class.forName("com.blah.MyActivity").getMethod('myFunction',String.class);
method.invoke(someInstanceOfMyActivity, stringValue);

It will work.

Documentation:
http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Method.html

Related Problems and Solutions