Java 9 替换 Class.newInstance

Java 9 replace Class.newInstance

Class.newInstance 在 Java 9:

中被弃用
clazz.newInstance()

can be replaced by

clazz.getDeclaredConstructor().newInstance()

问题是 getDeclaredConstructor returns 任何不考虑访问级别的构造函数。

如果我想替换代码中所有出现的地方(在不同的 packages/access 级别),我应该使用 getConstructor 来获取 public 构造函数吗?

the Constructor object of the public constructor that matches the specified parameterTypes

或者不能批量替换所有出现的地方,因为它需要每个案例(如果public构造函数存在 and/or 如果我有 class)?

的正确访问级别

编辑

getDeclaredConstructor:

   return getConstructor0(parameterTypes, Member.DECLARED);

获取构造函数:

   return getConstructor0(parameterTypes, Member.PUBLIC);

这两个调用调用同一个构造函数,即零参数构造函数:

  1. klass.newInstance()
  2. klass.getDeclaredConstructor().newInstance()

如果构造函数不是 public,则两者执行相同的 运行 次检查以验证调用者的访问权限。唯一的区别是#2 包装了任何已检查的异常,而不是直接抛出。否则它们是相同的,你可以用一个替换另一个。

但这次不一样:

  1. klass.getConstructor().newInstance()

因为它只能return一个public构造函数。如果构造函数不是 public.

,它会抛出一个 NoSuchMethodException

所以你不能把它改成getConstructor()除非你知道构造函数是public.