为什么是Class.newInstance()" evil"? [英] Why is Class.newInstance() "evil"?
问题描述
Ryan Delucchi 询问在这里在注释#3到 Tom Hawtin 的回答:
Ryan Delucchi asked here in comment #3 to Tom Hawtin's answer:
为什么是Class.newInstance()evil?
why is Class.newInstance() "evil"?
此回应代码示例:
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
那么,为什么是Evil?
so, why is it Evil?
推荐答案
Java API文档解释了为什么( http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()):
The Java API documentation explains why (http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()):
请注意,此方法传播由nullary构造函数抛出的任何异常,包括已检查的异常。使用此方法有效地绕过编译时异常检查,否则编译器将执行该异常检查。
Constructor.newInstance
方法通过将构造函数抛出的任何异常包装在(checked)InvocationTargetException
中来避免此问题。 / p>
Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The
Constructor.newInstance
method avoids this problem by wrapping any exception thrown by the constructor in a (checked)InvocationTargetException
.
换句话说,它可以取消检查的异常系统。
In other words, it can defeat the checked exceptions system.
这篇关于为什么是Class.newInstance()" evil"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!