简体   繁体   中英

How can I call Method.invoke with an arbitrary number of arguments?

I am building a system in which the user can type names of methods into a text file, and a java program will parse it, invoking methods in a separate class corresponding to the method name typed. The user also types all the arguments to the method in the file. Using Class.getMethods, I know the type and number of arguments that the desired method takes. I do not know how to call Method.invoke with the correct number of arguments given the number of arguments the method takes (which could be any number). Thanks in advance

Supply an Object[] array as the second argument of Method.invoke.

... is syntactic sugar for an array of that type, and is how the called method actually receives the values.

Inversely, this can be problematic if you actually want to supply an Object[] to the method, as you then need to wrap it once more.

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