I have below code which invokes a method using reflection. But I am getting,
java.lang.IllegalArgumentException: wrong number of arguments
exception at Method.invoke. What is the reason?
public class B {
public static void main(String[] args) {
A a = new A();
Method m;
try {
m = a.getClass().getMethod("m3",Integer.class);
m.invoke(a);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class A {
public void m3(Integer x){
System.out.println("ssss");
}
}
The invoke(Object, Object...)
-method takes as it's first parameter the object that the method should be invoked on (as you did correctly) and then as a variable-length parameter any parameters that should be passed to the method call.
In your case, you're forgetting about the methods Integer
-parameter. The method you're trying to call is A.m3()
, which doesn't exist in the class.
The correct call would be:
m.invoke(a, 12); // or any int/Integer as it's second parameter
Look at the original Method.invoke() method signature -
public Object invoke(Object obj,
Object... args)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
And it has no overloaded version. So your method call - m.invoke()
is not correct
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.