问题描述
好吧,我试图理解和阅读可能导致它的原因,但我就是无法理解:
Well, I've tried to understand and read what could cause it but I just can't get it:
我的代码中有这个:
try{
..
m.invoke(testObject);
..
} catch(AssertionError e){
...
} catch(Exception e){
..
}
事实是,当它试图调用某个方法时,它会抛出InvocationTargetException
而不是一些其他预期的异常(特别是 ArrayIndexOutOfBoundsException
).因为我实际上知道调用了什么方法,所以我直接转到此方法代码并为假设抛出 ArrayIndexOutOfBoundsException
的行添加了一个 try-catch 块,它确实抛出了 ArrayIndexOutOfBoundsException
作为预期的.然而当上去的时候以某种方式更改为 InvocationTargetException
和上面的代码 catch(Exception e)
e 是 InvocationTargetException
而不是 ArrayIndexOutOfBoundsException
正如预期的那样.
Thing is that, when it tries to invoke some method it throws InvocationTargetException
instead of some other expected exception (specifically ArrayIndexOutOfBoundsException
). As I actually know what method is invoked I went straight to this method code and added a try-catch block for the line that suppose to throw ArrayIndexOutOfBoundsException
and it really threw ArrayIndexOutOfBoundsException
as expected. Yet when going up it somehow changes to InvocationTargetException
and in the code above catch(Exception e)
e is InvocationTargetException
and not ArrayIndexOutOfBoundsException
as expected.
什么可能导致这种行为或者我如何检查这样的事情?
What could cause such a behavior or how can I check such a thing?
推荐答案
您通过反射调用方法添加了额外的抽象级别.反射层将任何异常包装在 InvocationTargetException
中,这让您可以区分实际上由反射调用失败引起的异常(也许您的参数列表不是有效,例如)和调用的方法失败.
You've added an extra level of abstraction by calling the method with reflection. The reflection layer wraps any exception in an InvocationTargetException
, which lets you tell the difference between an exception actually caused by a failure in the reflection call (maybe your argument list wasn't valid, for example) and a failure within the method called.
只需在 InvocationTargetException
中解开原因,您就会找到原来的原因.
Just unwrap the cause within the InvocationTargetException
and you'll get to the original one.
这篇关于什么可能导致 java.lang.reflect.InvocationTargetException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!