Java 9取代了Class.newInstance

use*_*900 14 java reflection constructor java-9

在Java 9中不推荐使用Class.newInstance:

clazz.newInstance()
Run Code Online (Sandbox Code Playgroud)

可以替换为

clazz.getDeclaredConstructor().newInstance()
Run Code Online (Sandbox Code Playgroud)

问题是getDeclaredConstructor返回任何构造函数而不考虑访问级别.

如果我想替换我的代码中的所有实例(在不同的包/访问级别),我应该使用getConstructor来获取公共构造函数吗?

与指定的parameterTypes匹配的公共构造函数的Constructor对象

或者我不能批量替换所有事件,因为它需要是每个案例(如果存在公共构造函数和/或我是否具有该类的正确访问级别)?

编辑

getDeclaredConstructor:

   return getConstructor0(parameterTypes, Member.DECLARED);
Run Code Online (Sandbox Code Playgroud)

getConstructor:

   return getConstructor0(parameterTypes, Member.PUBLIC);
Run Code Online (Sandbox Code Playgroud)

Boa*_*ann 9

klass.newInstance()调用零参数构造函数,无论它是否公开.它执行运行时检查调用者对该构造函数的访问权限.

调用klass.getDeclaredConstructor().newInstance()返回相同的构造函数.调用klass.getConstructor().newInstance()执行相同的运行时检查.除了对异常的不同处理外,它也做同样的事情.

不,不要改为NoSuchMethodException.这将导致getConstructor()非公共建设者.