Demo01_ConstructorTest.java 1.3 KB

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