[英]Java 9 replace Class.newInstance
Class.newInstance was deprecated in Java 9: 在Java 9中不推荐使用Class.newInstance :
clazz.newInstance()
can be replaced by
可以替换为
clazz.getDeclaredConstructor().newInstance()
The problem is that getDeclaredConstructor returns any constructor without regarding the access level. 问题是getDeclaredConstructor返回任何构造函数而不考虑访问级别。
If I want to replace all occurrences in my code (on different packages/access level) should I use getConstructor to get the public constructor? 如果我想替换我的代码中的所有实例 (在不同的包/访问级别),我应该使用getConstructor来获取公共构造函数吗?
the Constructor object of the public constructor that matches the specified parameterTypes
与指定的parameterTypes匹配的公共构造函数的Constructor对象
Or can't I bulk replace all occurrences because it needs to be per case (if a public constructor exists and/or if I have the right access level for the class)? 或者我不能 批量替换所有实例,因为它需要是每个案例(如果存在公共构造函数和/或我是否具有该类的正确访问级别)?
EDIT 编辑
getDeclaredConstructor: getDeclaredConstructor:
return getConstructor0(parameterTypes, Member.DECLARED);
getConstructor: getConstructor:
return getConstructor0(parameterTypes, Member.PUBLIC);
These two calls invoke the same constructor, the zero-argument constructor: 这两个调用调用相同的构造函数,即零参数构造函数:
klass.newInstance()
klass.getDeclaredConstructor().newInstance()
Both perform the same run-time check to verify the caller's access, if the constructor is not public. 如果构造函数不公开,则两者都执行相同的运行时检查以验证调用者的访问权限。 The only difference is that #2 wraps any checked exceptions instead of directly throwing.
唯一的区别是#2包装任何已检查的异常而不是直接抛出。 Otherwise they are identical and you can replace one with the other.
否则它们是相同的,你可以用另一个替换一个。
But this is different: 但这是不同的:
klass.getConstructor().newInstance()
because it can only return a public constructor. 因为它只能返回一个公共构造函数。 It throws a
NoSuchMethodException
if the constructor is not public. 如果构造函数不是公共的,它会抛出
NoSuchMethodException
。
So you can't change it to getConstructor()
unless you know the constructor is public. 因此,除非您知道构造函数是公共的,否则您无法将其更改为
getConstructor()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.