您的位置:首页 > 编程语言 > Java开发

java反射 java.lang.IllegalArgumentException: wrong number of arguments

2016-10-23 11:15 369 查看
很多人学习反射的时候,回碰到的一个异常,

举个例子:这个类里面有四个构造函数

public class Person {

public Person() {

}

public Person(String name) {
this.name = name;
}

public Person(int age) {
this.age = age;
}

public Person(String name, int age) {
this.age = age;
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "[" + this.name + " " + this.age + "]";
}

private String name;
private int age;
}


调用的时候
public static void test4(String className){
Class<?> demo1 = null;
try {
demo1=Class.forName(className);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

Person person1 = null;
Person person2 = null;
Person person3 = null;
Person person4 = null;

Constructor<?> cons[] = demo1.getConstructors();
try {
person1 = (Person) cons[0].newInstance();
person2 = (Person) cons[1].newInstance("xxx");
person3 = (Person) cons[2].newInstance(22);
person4 = (Person) cons[3].newInstance("xxx",22);
} catch (Exception e) {
e.printStackTrace();
}

System.out.println(person1);
System.out.println(person2);
System.out.println(person3);
System.out.println(person4);
}

这样子就会报错,原因在于,赋值的时候和构造函数里面顺序是相反的,希望网上教程不要拿过来复制,粘贴,自己也动动手,免得对初学者造成误导,写下!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐