7

I'm trying to invoke a method with variable arguments using java reflection. Here's the class which hosts the method:

public class TestClass {

public void setParam(N ... n){
    System.out.println("Calling set param...");
}

Here's the invoking code :

try {
        Class<?> c = Class.forName("com.test.reflection.TestClass");
        Method  method = c.getMethod ("setParam", com.test.reflection.N[].class);
        method.invoke(c, new com.test.reflection.N[]{});

I'm getting IllegalArgumentException in the form of "wrong number of arguments" at the last line where I'm calling invoke. Not sure what I'm doing wrong.

Any pointers will be appreciated.

  • Thanks
0

2 Answers 2

15
public class Test {

public void setParam(N... n) {
    System.out.println("Calling set param...");
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws Exception {
    Test t=new Test();
    Class<?> c = Class.forName("test.Test");
    Method  method = c.getMethod ("setParam", N[].class);
    method.invoke(t, (Object) new N[]{});
}
}

Works for me.

  1. Cast your N[] to Object
  2. call invoke on instance, not on class
Sign up to request clarification or add additional context in comments.

3 Comments

Tried that without cast to (Object) - I get the same exception as you did. So just add the cast (and correct point no 1) and you will be fine.
Right on, I was missing the cast to Object[]. Thanks a ton.
@Shamik: if you know the method you want to call you may avoid such issues using dp4j
3

There is no TestClass instance in your code snippet on which the methd is invoked. You need an instance of the TestClass, and not just the TestClass itself. Call newInstance() on c, and use the result of this call as the first argument of method.invoke().

Moreover, to make sure your array is considered as one argument, and not a varargs, you need to cast it to Object:

m.invoke(testClassInstance, (Object) new com.test.reflection.N[]{});

1 Comment

I thought so and tried that earlier. Here's what I did. Class<?> c = Class.forName("com.test.reflection.TestClass"); Object iClass = c.newInstance();Method method = c.getMethod ("setParam", com.test.reflection.N[].class); method.invoke(iClass , new com.test.reflection.N[]{}); I get "wrong number of arguments" exception.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.