Num*_*ron 5 java reflection exception-handling exception
我正在使用反射创建一个对象.根据构造的实际对象,构造函数可能具有特定自定义异常的throws声明,重要的是我可以捕获它.
不幸的是,当我尝试将异常添加到包含反射结构的try块的catch时,代码将无法编译,因为:
"无法访问的catch块.此异常永远不会从try语句主体中抛出"
我意识到捕获基类Exception会起作用,事实上我的代码也可以.然而,情况可能并非总是如此,因为未来其他对象可能适用于其他对象,并且在catch中使用instanceof并重新抛出其他所有内容似乎不够优雅.
有没有办法表明可能会抛出此异常,以便我可以专门捕获它?
编辑:根据要求编写一些代码.因为上面没有编译.
try{
Constructor<? extends Thing> constructor = getClassType().getDeclaredConstructor(SomeParameter.class);
Thing thing = constructor.newInstance(new SomeParameter());
}
catch(FoobarException e){
//new Thing(SomeParameter p) might throw this
}
catch(ReflectiveOperationException | IllegalArgumentException | SecurityException e){}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1497 次 |
| 最近记录: |