9

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
bushra
  • 133
  • 1
  • 1
  • 6

2 Answers2

15

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.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • Thanks and this is very helpful to me as well. But why we need to wrap this? I've tried even with an array of type object you still need to do this wrap, which I feel hard to understand. – Sam Y Jun 13 '21 at 12:49
  • 1
    @SamY Look at it like this: if your method accepts two `String` arguments, you need to send an array with two strings. If your methods accepts a `String` and a varargs `String...` argument, you need to send an array with a string (first argument) and an array of strings (second argument). – Robby Cornelissen Jun 14 '21 at 01:27
10

invoke expects an array of arguments.

In your case, you have 1 argument, of type array, so you should send an array of size 1, with 1 member, which is the first (and only) argument.

Like so:

Sample object = new Sample();
Method m = object.getClass().getMethod( "doSomething", String[].class );
String[] arr = {"v1","v2"};
Object[] methodArgs = new Object[] {arr};
m.invoke( object, methodArgs ); // no exception here
Yoav Gur
  • 1,366
  • 9
  • 15