con.setAccessible(True)
- 通过 .getDeclaredConstructor() 获得一个私有的构造器
- 对私有构造器的 accessble 设置为 true
- 进行对象创建
package 反射;
import java.sql.Struct;
public class Student {
private String name;
private int age;
private String address;
public Student(String name, int age, String address){
this.name = name;
this.age = age;
this.address = address;
}
private Student(String name){
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
package 反射;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Main {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<Student> studentClass = Student.class;
// Constructor<Student> constructor = studentClass.getConstructor(String.class, int.class, String.class);
// Student student = constructor.newInstance("青霞", 30, "西安");
// System.out.println(student);
Constructor<Student> cons = studentClass.getDeclaredConstructor(String.class);
cons.setAccessible(true);
Student student = cons.newInstance("青霞");
System.out.println(student);
}
}