嗯,我试着去理解和解读导致它的原因,但我就是不明白:

在我的代码中有这样的代码:

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

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.

是什么导致了这样的行为或者我如何检查这样的事情?


当前回答

调用目标异常:

我坚信,任何命名惯例都有勤奋的思想投入 在里面。而且,很有可能我们的问题都有他们的问题 答案就在名字里,如果我们试着找出名字背后的原因。

Let's break the name up into 3 parts. "Exception" has occurred when "Invoking" a "Target" method. And, the exception is thrown with this wrapper when, a method is invoked via reflection in Java. While executing the method, there could be any type of exception raised. It is by design, that the actual cause of the exception is abstracted away, to let the end user know that the exception was one that occurred during a reflection based method access. In order to get the actual cause, it is recommended that the exception is caught and ex.getCause() is called. Best practice is to, in fact throw the cause from the catch block that caught the InvocationTargetException

try{
    method.invoke();
} catch(InvocationTargetException ite) {
    throw ite.getCause();
} catch(Exception e) {
    // handle non-reflection originated exceptions
    throw e;
}

我知道它与其他答案类似,但我想更清楚地说明Java生成这种异常类型的“何时”,因此它对任何人来说都是一个谜。

其他回答

那个InvocationTargetException可能正在封装你的ArrayIndexOutOfBoundsException。在使用反射时,没有预先说明该方法可以抛出什么——因此,与使用抛出异常方法不同,所有异常都被捕获并封装在InvocationTargetException中。

我也面临着同样的问题。我使用e.getCause(). getcause(),然后我发现这是因为我传递了错误的参数。在获取其中一个参数的值时出现nullPointerException。 希望这对你有所帮助。

如果底层方法(使用Reflection调用的方法)抛出异常,则抛出此异常。

因此,如果反射API调用的方法抛出异常(例如运行时异常),反射API将把异常包装到InvocationTargetException中。

您可以使用getCause()方法与原始异常类进行比较,如下所示:

try{
  ...
} catch(Exception e){
   if(e.getCause().getClass().equals(AssertionError.class)){
      // handle your exception  1
   } else {
      // handle the rest of the world exception 
   }
} 

通过调用带有反射的方法,您增加了一个额外的抽象级别。反射层将任何异常包装在InvocationTargetException中,这使您可以区分实际由反射调用中的失败(例如,可能您的参数列表无效)引起的异常和所调用的方法中的失败。

只需在InvocationTargetException中展开原因,就会得到原始的原因。