如何使用Java Reflection调用引发异常的方法? [英] How to invoke a method which throws an Exception using Java Reflection?
问题描述
我想使用Java Reflection来调用一个方法。
I would like to invoke a method, using Java Reflection.
问题是这个方法(我写的)抛出一个异常(我创建了一个 myCustomException )。当我添加一个try / catch子句时,我无法运行我的项目,因为Eclipse提示 catch子句无法访问。
The problem is that this method (which I wrote) throws an Exception (I created a myCustomException). When I add a try/catch clause, I can't run my project, because Eclipse says "the catch clause is unreachable".
这里是我尝试调用的时间类别 MyClass 中的 myMethod :
Here is when I try to invoke myMethod in the class MyClass :
270. myMethod.invoke(null, myParam); // NB : null because myMethod is static
当 myMethod 不抛出时 MyCustomException ,一切都很好。但是当它抛出一个 MyCustomException 时,我收到此错误消息:
When myMethod does not throw a MyCustomException, eveything is fine. But when it throws a MyCustomException, I get this error message :
假设我尝试调用 fooMethod(),位于类 BarClass()和:
Let's say I try to invoke fooMethod(), which is in the class BarClass(), and :
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.tests.MyClass.test5(270)
at com.tests.MyClass.main(297)
Caused by: com.tests.MyCustomException
at com.tests.barClass.fooMethod(BarClass.java:129)
... 6 more
有可能吗?还是谢谢您。
Is it even possible ? Thanks for help anyway.
推荐答案
您可以找到造成这种情况的原因,这是原始的异常。
You can get the cause of it that would be the original exception.
InvocationTargetException.getCause();
来自文档:
InvocationTargetException是一个已检查的异常,该异常包装了由调用的方法或构造函数引发的
异常。
InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor.
http://docs.oracle.com/javase/6/docs/api/ java / lang / reflect / InvocationTargetException.html
在catch块中,您可以检查异常是否来自您期望的类型并进行处理。
In your catch block, you could check if exception is from the type you expect and handle it.
一种简单的方法是:
try {
...
} catch (InvocationTargetException ite) {
if (ite.getCause() instanceof SomeExceptionType) {
...
} else {
...
}
}
这篇关于如何使用Java Reflection调用引发异常的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!