Understanding java.lang.reflect.InvocationTargetException and why it occurs

In this post, we will see about java.lang.reflect.InvocationTargetException.

You might get java.lang.reflect.InvocationTargetException while working with reflection in java.

Reason for java.lang.reflect.InvocationTargetException

Reflection layer throws this exception when calling method or constructor throws any exception. java.lang.reflect.InvocationTargetException wraps underlying exception thrown by actual method or constructor call.

Let’s see this with the help of example:
Create a simple class named StringUtils.java. It will have method getLengthOfString() which does not have null handling, so when we pass null to this method, it will throw java.lang.NullPointerException.

Create anther class to call getLengthOfString using reflection.

Output:

java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.arpit.java2blog.ReflectionMain.main(ReflectionMain.java:16)
Caused by: java.lang.NullPointerException
at org.arpit.java2blog.StringUtils.getLengthOfString(StringUtils.java:7)
… 5 more

As you can see, we are getting java.lang.reflect.InvocationTargetException exception because of underlying NullPointerException.

Reflection layer wraps java.lang.reflect.InvocationTargetException around actual Exception to demostrate that this exception was raised during reflection API call.

Handle InvocationTargetException

As underlying exception is actual cause of InvocationTargetException, we can use Throwable's getCause() method to get actual underlyting exception and use it to log or rethrow the exception.

java.lang.NullPointerException
at org.arpit.java2blog.StringUtils.getLengthOfString(StringUtils.java:7)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at org.arpit.java2blog.ReflectionMain.main(ReflectionMain.java:16)

To resolve InvocationTargetException, you need to solve underlying Exception(NullPointerException) in above example.
Let’s handle the null check in StringUtils.java class and you won’t get any exception anymore.

Now when we run ReflectionMain.java again, you will see below output:

0

That’s all about java.lang.reflect.InvocationTargetException in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *