Java 用什么代替 Class.newInstance()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46393863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What to use instead of Class.newInstance()?
提问by Dmitri Nesteruk
Class.newInstance()
is marked deprecated. Documentation does not suggest any alternatives. How are we meant to create instances now?
Class.newInstance()
被标记为已弃用。文档不建议任何替代方案。我们现在打算如何创建实例?
采纳答案by Mureinik
To quote Java 9's javadoc:
The call
clazz.newInstance()
can be replaced by
clazz.getDeclaredConstructor().newInstance()
电话
clazz.newInstance()
可以替换为
clazz.getDeclaredConstructor().newInstance()
回答by Andy Turner
Class.getDeclaredConstructor(...).newInstance(...)
Refer to Google errorprone's documentation(for example) for a description of why.
有关原因的说明,请参阅Google errorprone 的文档(例如)。