Перейти к содержимому

Java lang reflect invocationtargetexception как исправить

  • автор:

Troubleshooting

This section contains examples of problems developers might encounter when using reflection to locate, invoke, or get information about methods.

NoSuchMethodException Due to Type Erasure

The MethodTrouble example illustrates what happens when type erasure is not taken into consideration by code which searches for a particular method in a class.

When a method is declared with a generic parameter type, the compiler will replace the generic type with its upper bound, in this case, the upper bound of T is Object . Thus, when the code searches for lookup(Integer) , no method is found, despite the fact that the instance of MethodTrouble was created as follows:

Searching for lookup(Object) succeeds as expected.

In this case, find() has no generic parameters, so the parameter types searched for by getMethod() must match exactly.

IllegalAccessException when Invoking a Method

An IllegalAccessException is thrown if an attempt is made to invoke a private or otherwise inaccessible method.

The MethodTroubleAgain example shows a typical stack trace which results from trying to invoke a private method in an another class.

The stack trace for the exception thrown follows.

IllegalArgumentException from Method.invoke()

Method.invoke() has been retrofitted to be a variable-arity method. This is an enormous convenience, however it can lead to unexpected behavior. The MethodTroubleToo example shows various ways in which Method.invoke() can produce confusing results.

Since all of the parameters of Method.invoke() are optional except for the first, they can be omitted when the method to be invoked has no parameters.

The code in this case generates this compiler warning because null is ambiguous.

It is not possible to determine whether null represents an empty array of arguments or a first argument of null .

This fails despite the fact that the argument is null , because the type is a Object and ping() expects no arguments at all.

This works because new Object[0] creates an empty array, and to a varargs method, this is equivalent to not passing any of the optional arguments.

Unlike the previous example, if the empty array is stored in an Object , then it is treated as an Object . This fails for the same reason that case 2 fails, ping() does not expect an argument.

InvocationTargetException when Invoked Method Fails

An InvocationTargetException wraps all exceptions (checked and unchecked) produced when a method object is invoked. The MethodTroubleReturns example shows how to retrieve the original exception thrown by the invoked method.

What Causes java.lang.reflect.InvocationTargetException?

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

When working with Java Reflection API, it is common to encounter java.lang.reflect.InvocationTargetException.

In this tutorial, we’ll take a look at it and how to handle it with a simple example.

2. Cause of InvocationTargetException

It mainly occurs when we work with the reflection layer and try to invoke a method or constructor that throws an underlying exception itself.

The reflection layer wraps the actual exception thrown by the method with the InvocationTargetException.

Let’s try to understand it with an example.

We’ll write a class with a method that intentionally throws an exception:

Let’s invoke the above method using reflection in a Simple JUnit 5 Test:

In the above code, we have asserted the InvocationTargetException, which is thrown while invoking the method. An important thing to note here is that the actual exception — ArithmeticException in this case — gets wrapped into an InvocationTargetException.

Now, why doesn’t reflection throw the actual exception in the first place?

The reason is that it allows us to understand whether the Exception occurred due to failure in calling the method through the reflection layer or whether it occurred within the method itself.

3. How to Handle InvocationTargetException?

Here the actual underlying exception is the cause of InvocationTargetException, so we can use Throwable.getCause() to get more information about it.

Let’s see how we can use getCause() to get the actual exception in the same example used above:

We’ve used the getCause() method on the same exception object that was thrown. And we have asserted ArithmeticException.class as the cause of the exception.

So, once we get the underlying exception, we can re-throw the same, wrap it in some custom exception or simply log the exception based on our requirement.

4. Conclusion

In this short article, we saw how the reflection layer wraps any underlying exception.

We also saw how to determine the underlying cause of the InvocationTargetException and how to handle such a scenario with a simple example.

As usual, the code used in this article is available over on GitHub.

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Что вызывает java.lang.reflect.Исключение InvocationTargetException?

Узнайте, что вызывает java.lang.reflect.Исключение InvocationTargetException.

  • Автор записи

1. Обзор

При работе с Java Reflection API часто встречается java.lang.reflect.InvocationTargetException . В этом уроке мы рассмотрим его и то, как с ним справиться, на простом примере .

2. Причина исключения InvocationTargetException

В основном это происходит, когда мы работаем со слоем отражения и пытаемся вызвать метод или конструктор, который сам создает базовое исключение.

Слой отражения обертывает фактическое исключение, вызванное методом, с помощью исключения InvocationTargetException . Давайте попробуем понять это на примере.

Давайте напишем класс с методом, который намеренно создает исключение:

Теперь давайте вызовем описанный выше метод, используя отражение в простом тесте JUnit 5:

В приведенном выше коде мы утвердили исключение InvocationTargetException , которое возникает при вызове метода. Здесь важно отметить, что фактическое исключение – ArithmeticException в данном случае – оборачивается в InvocationTargetException.

Теперь вопрос, который приходит на ум, заключается в том, почему отражение не создает фактическое исключение в первую очередь?

Причина в том, что это позволяет нам понять, произошло ли Исключение из-за сбоя при вызове метода через слой отражения или оно произошло внутри самого метода.

3. Как обрабатывать исключение InvocationTargetException?

Здесь фактическое базовое исключение является причиной InvocationTargetException , поэтому мы можем использовать Throwable.getCause () , чтобы получить дополнительную информацию об этом.

Давайте посмотрим, как мы можем использовать getCause() для получения фактического исключения в том же примере, который использовался выше:

Здесь мы использовали метод getCause() для того же объекта exception , который был брошен. И мы утверждали ArithmeticException.class как причина исключения.

Таким образом, как только мы получим базовое исключение, мы можем перестроить его, обернуть в какое-то пользовательское исключение или просто зарегистрировать исключение в соответствии с нашими требованиями.

4. Заключение

В этой короткой статье мы рассмотрели, как слой отражения обертывает любое базовое исключение. Мы также видели, как определить основную причину исключения InvocationTargetException и как справиться с таким сценарием на простом примере.

What could cause java.lang.reflect.InvocationTargetException?

Well, I’ve tried to understand and read what could cause it but I just can’t get it:

I have this somewhere in my code:

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.

What could cause such a behavior or how can I check such a thing?

15 Answers 15

You’ve added an extra level of abstraction by calling the method with reflection. The reflection layer wraps any exception in an InvocationTargetException , which lets you tell the difference between an exception actually caused by a failure in the reflection call (maybe your argument list wasn’t valid, for example) and a failure within the method called.

Just unwrap the cause within the InvocationTargetException and you’ll get to the original one.

To do that, you can do exception.printStackTrace() and look at the "Caused By:" section instead of the top half/normal section.

You can also catch the exception and use the getCause() method on it, which can also be re-thrown, if desired. Something like try <. >catch (InvocationTargetException ex) < log.error("oops!", ex.getCause()) >or . catch.

The exception is thrown if

InvocationTargetException — if the underlying method throws an exception.

So if the method, that has been invoked with reflection API, throws an exception (runtime exception for example), the reflection API will wrap the exception into an InvocationTargetException .

Use the getCause() method on the InvocationTargetException to retrieve the original exception.

From the Javadoc of Method.invoke()

Throws: InvocationTargetException — if the underlying method throws an exception.

This exception is thrown if the method called threw an exception.

gEdringer's user avatar

This will print the exact line of code in the specific method, which when invoked, raised the exception:

ROMANIA_engineer's user avatar

That InvocationTargetException is probably wrapping up your ArrayIndexOutOfBoundsException . There is no telling upfront when using reflection what that method can throw — so rather than using a throws Exception approach, all the exceptions are being caught and wrapped up in InvocationTargetException .

Liv's user avatar

This describes something like,

InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor. As of release 1.4, this exception has been retrofitted to conform to the general purpose exception-chaining mechanism. The «target exception» that is provided at construction time and accessed via the getTargetException() method is now known as the cause, and may be accessed via the Throwable.getCause() method, as well as the aforementioned «legacy method.»

Sazzad Hissain Khan's user avatar

You can compare with the original exception Class using getCause() method like this :

I had a java.lang.reflect.InvocationTargetException error from a statement calling a logger object in an external class inside a try / catch block in my class .

Stepping through the code in the Eclipse debugger & hovering the mouse over the logger statement I saw the logger object was null (some external constants needed to be instantiated at the very top of my class ).

A problem can also be that the targetSdkVersion is upped and that you use deprecated Gradle manifest features. Try lowering the targetSdkVersion again and see if it works. In my case it was targetSdkVersion 31 -> 30

This exception is thrown if the underlying method(method called using Reflection) throws an exception.

So if the method, that has been invoked by reflection API, throws an exception (as for example runtime exception), the reflection API will wrap the exception into an InvocationTargetException.

I was facing the same problem. I used e.getCause().getCause() then I found that it was because of wrong parameters I was passing. There was nullPointerException in fetching the value of one of the parameters. Hope this will help you.

Deepak Vajpayee's user avatar

Invocation Target Exception:

I strongly believe that any naming convention has diligent thoughts invested in it. And, it is more than likely that our questions have their answers in the names, if we tried finding a rationale behind the name.

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

I know it is similar to the other answers, but I wanted to make it more clear about "when" this exception type is generated by Java, so that it is a mystery to none.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *