I have a list of parameters, and I have a method name. I want to call a method using reflection. When I checked the java document for Method.invoke, it looks like Method.invoke (object o, Object args ...). I know what to pass for the first parameter (for example, for a method that should be called if its instance method) and args are parameters for the method.
But now I have a list that contains the values ββthat should be passed to the method.
Let's say for example: I want to call the ClassName.methodName (String, int, int) method, and I have a List that contains {val1, 3, 4}.
Using reflection may be similar to Method.invoke (classNameInstance, ??????). But I'm not sure how to convert the argument list to varargs and pass.
One way could be. If I know that the size of the list is 3, then I can write Method.invoke (classNameInstance, list.get (0), list.get (1), list.get (2)).
But some of the methods that I want to dynamically call take from 0 to 12 arguments. So it does not look βgoodβ to create a switch case and record 12 cases. Each of them will check the number of parameters and build a separate call with parameters.
Is it possible to get around this, except using the switching case?
Any help would be greatly appreciated.
source
share