package J20250806.reflection; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /** * @author WanJl * @version 1.0 * @title ConstructorTest01 * @description 通过反射,获取Person类的私有构造方法并创建对象 * @create 2025/8/6 */ public class Demo01_ConstructorTest { public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { //通过类名.class反射方式获取Person类的Class对象 Class personClass = Person.class; //通过personClass对象获取Person类的构造方法,无论是否是私有化的。由于没有填写参数类型,因此是获取无参的 Constructor personConstructor = personClass.getDeclaredConstructor(); System.out.println(personConstructor); //如果目标构造方法是私有的,那么需要调用一个方法,增加取消检查标志 personConstructor.setAccessible(true); //暴力反射 //使用反射,构造方法创建对象 Person person = personConstructor.newInstance(); person.setId(15); person.setName("张三"); person.setAge(26); person.setSex("男"); System.out.println(person); } }