什么可能导致java.lang.reflect.InvocationTargetException? [英] What could cause java.lang.reflect.InvocationTargetException?

查看:187
本文介绍了什么可能导致java.lang.reflect.InvocationTargetException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,我试图理解和阅读可能导致什么,但是我无法得到它:

Well, I've tried to understand and read what could cause it but I just can't get it:

我的代码中有一些地方: / p>

I have somewhere in my code this:

 try{
 ..
 m.invoke(testObject);
 ..
 } catch(AssertionError e){
 ...
 } catch(Exception e){
 ..
 }

事实是,当它尝试调用一些方法时,它会抛出
InvocationTargetException 而不是一些其他预期的异常(具体来说是 ArrayIndexOutOfBoundsException )。
因为我实际上知道调用了什么方法,我直接去了这个方法代码,并添加了一个try-catch块,假设抛出 ArrayIndexOutOfBoundsException ,它真的抛出 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆