我想调用一个方法,使用 Java 反射。
问题是这个方法(我写的)抛出一个异常(我创建了一个myCustomException)。当我添加一个 try/catch 子句时,我无法运行我的项目,因为 Eclipse 说“catch 子句不可达”。
这是当我尝试在类 MyClass 中调用 myMethod 时:
270. myMethod.invoke(null, myParam); // NB : null because myMethod is static
当 myMethod 没有抛出 MyCustomException 时,一切正常。但是当它抛出 MyCustomException 时,我收到了这个错误消息:
假设我尝试调用类 BarClass() 中的 fooMethod(),并且:
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
有可能吗?无论如何,感谢您的帮助。
最佳答案
您可以找到原始异常的原因。
InvocationTargetException.getCause();
来自文档:
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 block 中,您可以检查异常是否来自您期望的类型并处理它。
一个简单的方法是:
try {
...
} catch (InvocationTargetException ite) {
if (ite.getCause() instanceof SomeExceptionType) {
...
} else {
...
}
}
关于java - 如何使用 Java 反射调用抛出异常的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11452021/