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

后端 未结 3 1672
终归单人心
终归单人心 2020-12-31 02:37

I would like to invoke a method, using Java Reflection.

The problem is that this method (which I wrote) throws an Exception (I created a myCustomException).

相关标签:
3条回答
  • 2020-12-31 03:19

    One way to do it:

    try { myMethod.invoke(null, myParam); }
    catch (InvocationTargetException e) { 
      try { throw e.getCause(); }
      catch (MyCustomException e) { ...}
      catch (MyOtherException e) { ...}
    }
    
    0 讨论(0)
  • 2020-12-31 03:22

    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 {
          ...
       }
    }
    
    0 讨论(0)
  • 2020-12-31 03:26

    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.

    0 讨论(0)
提交回复
热议问题