I have a list of parameters and I have the method name. I want to invoke the method using reflection. When I checked the java doc for Method.invoke its like Method.invoke(object o, Object args...) . I know what to pass for the first paramter (i.e instance on which method to be invoked if its instance method) and args is the parameters for the method.
But now I have have the list which contains values which are to be passed to the method.
Say for example: I want to invoke method ClassName.methodName(String , int, int) and I have a List which contains {val1, 3, 4}.
Using reflection it may be like Method.invoke (classNameInstance, ??????). But I am not sure how to convert a list of arguments to varargs and pass.
One way may be If i know that list size is 3 then I may write Method.invoke (classNameInstance, list.get(0), list.get(1), list.get(2)).
But some of the methods which I want to dynamically invoke take 0 to 12 arguments. So it doesn't look "good" to create switch case and write 12 cases. Each will check with number of parameters and build the separate call with parameters.
Any way to go about this except from using switch case?
Any help will be greatly appreciated.
The Notation Object... means nothing more than Object[]. It is just syntactic sugar for an Arraynotation. Pass an Array and it will work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With