什么可能导致java.lang.reflect.InvocationTargetException?

编程入门 行业动态 更新时间:2024-10-24 21:28:28
本文介绍了什么可能导致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?

本文发布于:2023-10-28 23:36:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538097.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:lang   java   InvocationTargetException   reflect

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!