反射小问题
package cn.itcast.test;
import java.lang.reflect.Constructor;
import
java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Person {
private String name;
private int age;
Person(){
}
Person(String name,int age){
this.name=name;
this.age=age;
}
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;
}
}
public class PersonTest{
public static void main(String[] args) {
Class<Person> personClass;
try {
personClass = (Class<Person>) Class.forName("cn.itcast.test.Person");
Person person= (Person) personClass.newInstance();
person.setName("zhangsan");
System.out.println(person.getName());
Constructor constructor=person.getClass().getConstructor(String.class,int.class);//为何报:
java.lang.NoSuchMethodException: cn.itcast.test.Person.<init>(java.lang.String, int)
person=(Person) constructor.newInstance("aaa",22);
System.out.println(person.getAge());
Method method=personClass.getMethod("setName", String.class);
method.invoke(person, "lisi");
System.out.println(person.getName());
} catch (
ClassNotFoundException e1) {
e1.printStackTrace();
} catch (
InstantiationException e) {
e.printStackTrace();
} catch (
IllegalAccessException e) {
e.printStackTrace();
} catch (
SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (
IllegalArgumentException e) {
e.printStackTrace();
} catch (
InvocationTargetException e) {
e.printStackTrace();
}
}
}
------解决方案--------------------目测那不是一个public的构造方法
要用getDeclaredConstructors
------解决方案--------------------getConstructor只能获取public修饰符的构造方法,你可以在Person那个带2个参数的构造方法前加public修饰,或者按照楼上的方法用getDeclaredConstructors可以获得所有的,不受修饰符限制。
------解决方案--------------------其實
我只是
手震打多了個s
我是想說 getDeclaredConstructor