gpt4 book ai didi

java - 捕获java反射中的特定异常

转载 作者:太空宇宙 更新时间:2023-11-04 09:45:55 25 4
gpt4 key购买 nike

给定一个具有静态方法的类并抛出一些异常

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?

最佳答案

您无法捕获该异常的原因是 Method::invoke ( javadoc ) 不会抛出它!

如果您通过 invoke 调用的方法抛出任何异常,反射层会捕获该异常,然后创建并抛出一个 InvocableTargetException ( javadoc ),并将原始异常作为异常的原因

所以这就是你需要做的:

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.
}
}
}

关于java - 捕获java反射中的特定异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55428080/

25 4 0
文章推荐: python - 如何获得 XGBClassifier 的预测 p 值?
文章推荐: linux - 您如何找到启动所需的时间?
文章推荐: html -
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com