Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get Java.lang.IllegalArgumentException: wrong number of arguments while invoking a method with varargs using Reflection [duplicate]

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
like image 734
bushra Avatar asked Feb 02 '18 07:02

bushra


People also ask

What is IllegalArgumentException in Java with example?

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).

Can we catch IllegalArgumentException?

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.


1 Answers

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.

like image 174
Robby Cornelissen Avatar answered Oct 27 '22 01:10

Robby Cornelissen