use*_*900 14 java reflection constructor java-9
在Java 9中不推荐使用Class.newInstance:
Run Code Online (Sandbox Code Playgroud)clazz.newInstance()可以替换为
Run Code Online (Sandbox Code Playgroud)clazz.getDeclaredConstructor().newInstance()
问题是getDeclaredConstructor返回任何构造函数而不考虑访问级别.
如果我想替换我的代码中的所有实例(在不同的包/访问级别),我应该使用getConstructor来获取公共构造函数吗?
与指定的parameterTypes匹配的公共构造函数的Constructor对象
或者我不能批量替换所有事件,因为它需要是每个案例(如果存在公共构造函数和/或我是否具有该类的正确访问级别)?
编辑
getDeclaredConstructor:
Run Code Online (Sandbox Code Playgroud)return getConstructor0(parameterTypes, Member.DECLARED);
getConstructor:
Run Code Online (Sandbox Code Playgroud)return getConstructor0(parameterTypes, Member.PUBLIC);
klass.newInstance()调用零参数构造函数,无论它是否公开.它执行运行时检查调用者对该构造函数的访问权限.
调用klass.getDeclaredConstructor().newInstance()返回相同的构造函数.调用klass.getConstructor().newInstance()执行相同的运行时检查.除了对异常的不同处理外,它也做同样的事情.
不,不要改为NoSuchMethodException.这将导致getConstructor()非公共建设者.
| 归档时间: |
|
| 查看次数: |
3108 次 |
| 最近记录: |