为什么 Class.newInstance() 是“邪恶的"? [英] Why is Class.newInstance() "evil"?
问题描述
Ryan Delucchi 问此处 评论 #3 到 汤姆霍廷的回答:
Ryan Delucchi asked here in comment #3 to Tom Hawtin's answer:
为什么 Class.newInstance() 是邪恶的"?
why is Class.newInstance() "evil"?
这是对代码示例的回应:
this in response to the code sample:
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
那么,为什么是邪恶的?
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()):
请注意,此方法会传播空构造函数抛出的任何异常,包括已检查的异常.使用此方法可以有效地绕过编译器否则会执行的编译时异常检查.Constructor.newInstance
方法通过将构造函数抛出的任何异常包装在(已检查的)InvocationTargetException
中来避免此问题.
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() 是“邪恶的"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!