Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments

public class demo {
    public static void main(String[] args) throws Exception {
        Class p = Person.class;
        Person person = p.newInstance();
        String[]  str = {"大王","小王"};
        Method method = p.getMethod("list", String[].class);
        method.invoke(person,str);
    }
}
public class Person {

    public void list(String[] str){
        System.out.println(Arrays.toString(str));
    }
}
Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:564)
	at com.字符数当参的问题.demo.main(demo.java:19)

由于 Method method = p.getMethod("list", String[].class);方法只有一个String数组的参数所以这时编译器会把字符串数组当作一个可变长度参数传给对象str,而我们取得方法只有一个参数,所以就会出现wrong number of arguments的异常,我们只要把字符串数组强制转换为一个Object对象就可以解决这个异常了p.getMethod("list", String[].class);;就解决了;

你可能感兴趣的:(解bug,java)