How to invoke a method which throws an Exception using Java Reflection?

≯℡__Kan透↙ 提交于 2019-11-30 08:34:09

You can get the cause of it that would be the original exception.

InvocationTargetException.getCause();

From documentation:

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

In your catch block, you could check if exception is from the type you expect and handle it.

One simple approach would be:

try {
   ...
} catch (InvocationTargetException ite) {
   if (ite.getCause() instanceof SomeExceptionType) {
      ...
   } else {
      ...
   }
}

One way to do it:

try { myMethod.invoke(null, myParam); }
catch (InvocationTargetException e) { 
  try { throw e.getCause(); }
  catch (MyCustomException e) { ...}
  catch (MyOtherException e) { ...}
}

If you are trying to add a catch clause in the method that executes myMethod.invoke(null, myParam), then that's obviously not the right way of doing it. In this case you're invoking the method via reflection and this is not the place to be catching the exception, as the invoke method throws other exceptions. Once you invoke the method that throws the exception, if there is an exception, it will get thrown and wrapped in an InvocationTargetException, if I recall correctly.

Check the last part of this explanation concerning the InvocationTargetException.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!