Java / Android Call method from WITH Value string

Say I have a method that I want to call that has a string argument

To call, I would do something like this .. turRipsYop (stringValue);

NOW, how would I make the same call, but dynamically, if I had a string with the value 'myFunction' ..

sort of

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

I'm currently trying something like

java.lang.reflect.Method method;

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

but receiving an IllegalArgumentException error Message expected receiver type com.blah.MyActivity, but received java.lang.String

+4
source share
2 answers

Instruction:

 method.invoke (stringValue); 

the object in which method will be called is required.

So, if you try something like:

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

he will work.

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

+3
source

Follow my comments above:

do this to call com.blah.MyActivity::myFunction :

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

(forgive C ++ syntax)

I will try to explain why it works as follows:

A method is just a special type of function. This is a convenience created for people to deal with classes and objects.

As you know, inside the method you always have the this variable .. behind these scenes, this is passed as a parameter, but the following is written instead:

 com.blah.MyActivity activity = new com.blah.MyActivity() ; com.blah.MyActivity::myFunction( activity, stringValue ) 

you can easily write this:

 com.blah.MyActivity activity = new com.blah.MyActivity() ; activity.myFunction(stringValue) 

When you get a method using reflection, it's just a "normal function". To call it directly, you need to pass the this parameter.

That's why you have errors like ... myFunction expects the first hidden argument to be an instance of it, containing the class you skipped.

NTN

+3
source

All Articles