Constructor的反射:
public void testConstructor() {
Class clazz = Student.class;
Constructor[] constructors = clazz.getDeclaredConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
System.out.println(constructor.getName());//构造方法的名字
System.out.println(constructor.getModifiers());//修饰符
}
}
public com.situ.day15.Student()
com.situ.day15.Student
1
private com.situ.day15.Student(java.lang.String)
com.situ.day15.Student
2
@Test
public void testConstructor2() throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class clazz = Student.class;
//得到指定参数的构造方法
Constructor constructor = clazz.getDeclaredConstructor(String.class);
System.out.println(constructor);
constructor.setAccessible(true);//加上之后就可以访问私有构造方法
//Student student1 = new Student("zhansgan");
Student student = (Student) constructor.newInstance("zhansgan");
System.out.println(student);
}
private com.situ.day15.Student(java.lang.String)
Student [name=zhansgan]
public void testMethod() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//Student student = new Student();
//student.setName("lisi");
Class clazz = Class.forName("com.situ.day15.Student");
//得到无参构造方法
Constructor constructor = clazz.getConstructor();
//调用newInstance实例化对象
Student student = (Student) constructor.newInstance();
//student.setName("lisi");
Method method = clazz.getMethod("setName", String.class);
method.invoke(student, "lisi");
System.out.println(student);
}