简体   繁体   中英

Java/Android Call method from string WITH Value

Say I have a method that I wish to call which has an argument of a string

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

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

something like

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

I am currently trying something like

java.lang.reflect.Method method;

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

but getting the error IllegalArgumentException Message expected receiver of type com.blah.MyActivity, but got java.lang.String

The instruction:

method.invoke (stringValue);

needs the object in which the method will be invoked.

So, if you try something like:

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

Follow up to my comment above:

do this to invoke 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 the c++ syntax)

I'll try to explain why it works like this:

A method is really just a special type of function.. it's a convenience created to let people deal with classes and objects..

As you know, inside a method you always have a this variable.. behind this scenes, this is passed in as a parameter, but instead writing this:

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

you can conveniently write this:

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

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

That's why you are having type errors... myFunction expects the first hidden argument to be an instance of it's containing class, which you omitted.

HTH

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