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
There is no
TestClass
instance in your code snippet on which the methd is invoked. You need an instance of theTestClass
, and not just theTestClass
itself. CallnewInstance()
onc
, and use the result of this call as the first argument ofmethod.invoke()
.Moreover, to make sure your array is considered as one argument, and not a varargs, you need to cast it to Object:
Works for me.