【发布时间】:2015-05-02 19:03:30
【问题描述】:
据此:https://docs.oracle.com/javase/tutorial/reflect/member/ctorTrouble.html
Class.newInstance() 抛出意外异常 ConstructorTroubleToo 示例显示了 Class.newInstance() 中无法解决的问题。也就是说,它会传播构造函数抛出的任何异常(已检查或未检查)。
这种情况是反射所独有的。通常,不可能编写忽略已检查异常的代码,因为它不会编译。可以使用 Constructor.newInstance() 而不是 Class.newInstance() 来包装构造函数抛出的任何异常。
下面我有一个代码,它没有捕获任何未经检查的 (RuntimeEcxeption/Error) 异常,我对它们进行了注释并编译。那么这种传播在哪里呢?我编写的代码忽略了被告知不可能的未经检查的异常。请解释一下关于上述引用的 Class.newInstance() 有什么问题?
try {
Class<?> c = Class.forName("ConstructorTroubleToo");
// Method propagetes any exception thrown by the constructor
// (including checked exceptions).
Object o = c.newInstance();
// production code should handle these exceptions more gracefully
} catch (ClassNotFoundException |
InstantiationException |
IllegalAccessException x
/*IllegalArgumentException |
SecurityException x*/ ) {
x.printStackTrace();
}
【问题讨论】:
标签: java