Reputation: 1
When I call java.lang.reflect.Method.invoke() method on a private static method, I get a "java.lang.IllegalArgumentException : wrong number of arguments". I think I respect javadoc specification, did I something wrong ? Thanks for any help.
Here is my code :
public class MyClass {
....
private static Object myMethod(String[] stringArray) {...}
}
I want to test myMethod() in a JUnit test class :
public class MyClassTest {
private static String[] myArray = {"A", "B", "C"};
@Test
public void myMethodTest() {
Method method = Class.forName("mypackage.MyClass").getDeclaredMethod("myMethod", myArray.getClass());
method.setAccessible(true);
method.invoke(null, myArray);
}
}
Upvotes: 0
Views: 426
Reputation: 97341
You need to wrap your String
in an object array:
Method method = Class.forName("mypackage.MyClass")
.getDeclaredMethod("myMethod", myArray.getClass());
method.setAccessible(true);
method.invoke(null, new Object[] {myArray});
The second parameter to method.invoke()
requires an array or vararg of the method's arguments. For your method, you only have a single argument (which also happens to be an array), but you still need to wrap it in an array.
Upvotes: 0
Reputation: 692181
Since invoke()
takes a vararg as argument, the Java compiler considers each element of the array that you pass as a vararg argument, i.e. it considers it equivalent to
method.invoke(null, "A", "B", "C");
You can just cast your array to an object to fix the issue:
method.invoke(null, (Object) myArray);
Upvotes: 2