给一个带有静态方法的类并抛出一些异常
class Foo {
public static void doThis() throws CannotDoThisException {
//do something
}
}
我正在使用以下反射来调用doThis方法
public class Bar {
Class c = Class.forName("Foo");
Method m = c.getDeclaredMethod("doThis",null);
try {
m.invoke(null,null);
} catch (CannotDoThisException e) {
//Compiler says this is unreachable block.
}
}
如何捕获CannotDoThisException异常?
答案 0 :(得分:0)
您无法捕获该异常的原因是Method::invoke
(javadoc)不会抛出该异常!
如果您通过invoke
调用的方法抛出 any 异常,则反射层将捕获该异常,然后创建并抛出InvocationTargetException
(javadoc)并将原始异常作为异常的cause
。
这就是您需要做的:
public class Bar {
Class c = Class.forName("Foo");
Method m = c.getDeclaredMethod("doThis",null);
try {
m.invoke(null,null);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof CannotDoThisException) {
// do something about it
} else {
// do something else
// if the `cause` exception is unchecked you could rethrow it.
}
}
}