I have a method in a class as below
class Sample{
public void doSomething(String ... values) {
//do something
}
public void doSomething(Integer value) {
}
}
//other methods
.
.
.
Now I get IllegalArgumentException: wrong number of arguments below
Sample object = new Sample();
Method m = object.getClass().getMethod( "doSomething", String[].class );
String[] arr = {"v1","v2"};
m.invoke( object, arr ) // exception here
An IllegalArgumentException is thrown in order to indicate that a method has been passed an illegal argument. This exception extends the RuntimeException class and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM).
Because IllegalArgumentException is an unchecked exception, the Java compiler doesn't force you to catch it. Neither do you need to declare this exception in your method declaration's throws clause. It's perfectly fine to catch IllegalArgumentException , but if you don't, the compiler will not generate any errors.
Wrap your String
array in an Object
array:
Sample object = new Sample();
Method m = object.getClass().getMethod("doSomething", String[].class);
String[] arr = {"v1", "v2"};
m.invoke(object, new Object[] {arr});
A varargs argument, even though it may be comprised of multiple values, is still considered to be one single argument. Since Method.invoke()
expects an array of arguments, you need to wrap your single varargs argument into an arguments array.
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