【‘newInstance()‘ 已经过时了】

左手的ㄟ右手 2023-09-26 16:22 206阅读 0赞

问题:‘newInstance()’ 已经过时了

  1. User user = (User) class1.newInstance();

在这里插入图片描述

原因:jdk9 之后,对newInstance()做了些改变(截取了参数说明)

  1. * @param initargs array of objects to be passed as arguments to
  2. * the constructor call; values of primitive types are wrapped in
  3. * a wrapper object of the appropriate type (e.g. a {
  4. @code float}
  5. * in a {
  6. @link java.lang.Float Float})
  7. *
  8. * @return a new object created by calling the constructor
  9. * this object represents
  10. *
  11. @CallerSensitive
  12. @ForceInline // to ensure Reflection.getCallerClass optimization
  13. public T newInstance(Object ... initargs)
  14. throws InstantiationException, IllegalAccessException,
  15. IllegalArgumentException, InvocationTargetException
  16. {

解决:当前版本jdk11

  1. package com.example.demomain.reflectstudy;
  2. import org.junit.jupiter.api.Test;
  3. import java.lang.reflect.Constructor;
  4. import java.lang.reflect.InvocationTargetException;
  5. public class GetInstance {
  6. /*
  7. * 调用运行时类的构造器:
  8. * */
  9. @Test
  10. public void testConstructor() throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
  11. //获取指定参数为String的构造器
  12. Constructor constructor1 = User.class.getDeclaredConstructor(String.class);
  13. //2.保证此构造器是可访问的
  14. constructor1.setAccessible(true);
  15. //3.调用此构造器创建运行时类的对象
  16. //方法一:jdk9之前
  17. //User user = (User)clazz.newInstance();
  18. //方法二:jdk9之后: 参数为 Constructor 指定的构造参数
  19. User user = (User) constructor1.newInstance("lfsun");
  20. user.print();
  21. //获取指定无参构造器
  22. Constructor constructor2 = User.class.getDeclaredConstructor();
  23. constructor2.setAccessible(true);
  24. User user1 = (User) constructor2.newInstance();
  25. // 引用类型默认为 null
  26. user1.print();
  27. }
  28. }

涉及到的实体类:

  1. package com.example.demomain.reflectstudy;
  2. /**
  3. * @author lfsun
  4. */
  5. public class User {
  6. private String userName;
  7. User(String userName) {
  8. this.userName = userName;
  9. }
  10. User() {
  11. }
  12. public void print() {
  13. System.out.println("Hello World " + userName);
  14. }
  15. }

发表评论

表情:
评论列表 (有 0 条评论,206人围观)

还没有评论,来说两句吧...

相关阅读