Retrieve the *real* exception thrown from a method reflectively invoked

java, reflection

Solution

The javadoc for `InvocationTargetException` states

InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor.

Just call `InvocationTargetException#getCause()` to get the wrapped exception (or `getTargetException()` if you want to be old-school).

Problem

Say I have a method foo() declared below. ``` public class Foo { public static void foo() {throw new UnsupportedOperationException();} } ``` Then I have code that invoked the method using reflection: ``` Foo.class.getMethod("foo").invoke(); ``` This would throw `InvocationTargetException` rather than the `UnsupportedOperationException` that is actually thrown in the method. How do I retrieve the real exception (ie., the UnsupportedOperationException) with Java's reflection?

Original source