简体   繁体   中英

Method.invoke what parameter it can take?

I have the method name in string which has to be invoked dynamically. Method name.invoke(object,parameters) In the above format what should the object be? Should it be always creater by createNewInstance method? How can I use an already constructed object instead of it?

what should the object be?

If the method is static , the object parameter should be null .

If the method is not static , the object parameter should be the object you want to call the method on, ie the object that will be the value of this inside the method.

Should it be always creater by createNewInstance method?

No.

How can I use an already constructed object instead of it?

Give the "already constructed object" as the object parameter value.


Example

Normally, you would call a method like this:

myObj.foo("bar");

To make the same call using reflection:

Method m = myObj.getClass().getMethod("foo", String.class);
m.invoke(myObj, "bar");

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