Меню Закрыть

Java lang reflect invocationtargetexception null

Ну, я пытался понять и прочитать, что может вызвать это, но я просто не могу это понять:

У меня это где-то в моем коде:

Дело в том, что когда он пытается вызвать какой-либо метод, он выдает InvocationTargetException вместо некоторого другого ожидаемого исключения (в частности, ArrayIndexOutOfBoundsException ). Поскольку я действительно знаю, какой метод вызывается, я пошел прямо к этому методу кода и добавил блок try-catch для строки, которая предположила бы выбросить ArrayIndexOutOfBoundsException и она действительно выбросила ArrayIndexOutOfBoundsException как ожидалось. Тем не менее, когда он поднимается, он каким-то образом изменяется на InvocationTargetException и в коде выше catch(Exception e) e является InvocationTargetException а не ArrayIndexOutOfBoundsException как ожидалось.

Что может вызвать такое поведение или как я могу это проверить?

Вы добавили дополнительный уровень абстракции, вызвав метод с отражением. Отражающий слой обертывает любое исключение в InvocationTargetException , которое позволяет рассказать о различии между исключением, фактически вызванным сбоем в вызове отражения (возможно, например, ваш список аргументов недействителен) и сбой в методе, называемом.

Просто распакуйте причину в InvocationTargetException , и вы перейдете к исходному.

Исключение выбрано, если

InvocationTargetException — если базовый метод генерирует исключение.

Итак, если метод, который был вызван с API-интерфейсом отражения, генерирует исключение (например, исключение среды выполнения), API-интерфейс отражения превратит исключение в InvocationTargetException .

I have a REST API project in jersey and hk2 used. Now, I convert is to spring boot project and keep jersey endpoints and DI in hk2. it seems that it is working except the following error. But I have no idea why the following error happens. Any hints welcomed. I will provide more details as requested. I have no idea what the error is about.

Читайте также:  Что делать с битыми секторами на hdd

part of persistence.xml

1 Answer 1

They recommended set property (I believe it’s the best workaround):

as workaround is to disable hibernate to detect this function by setting flag hibernate.jdbc.lob.non_contextual_creation=true

Disable feature detection by this undocumented parameter. Check the org.hibernate.engine.jdbc.internal.JdbcServiceImpl.configure method for more details. spring.jpa.properties.hibernate.temp.use_jdbc_metadata_defaults = false

So you can also try to add to your Spring boot properties file

Posted by: Sotirios-Efstathios Maneas in exceptions December 31st, 2013 0 Views

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java Virtual Machine. The reflection layer wraps any thrown exception as an InvocationTargetException . In this way, it is clear whether the exception was actually caused by a failure in the reflection call, or a failure within the method called.

The InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor. The thrown exception is provided at construction time and can be accessed via the getTargetException method. That exception is known as the cause and can be accessed via the getCause method.

For more information about the reflection in Java, please refer to the page here .

Error case

The following code snippet throws an InvocationTargetException :

The result of the above snippet is:

If we carefully observe the code, we will understand why the InvocationTargetException was thrown. Initially, we get an instance of the ReflectionExample class. Then, we iterate over its declared methods and we call the method under the name testMethod , passing an empty String as an argument.

However, the testMethod throws an IllegalArgumentException , in case the length of the string equals to zero. That exception is wrapped as an InvocationTargetException and is thrown in our sample application.

Читайте также:  Как открыть вай фай на компе

If we change the 39 th line to:

the execution continues without any exception being thrown. As a result, we get the following result:

How to deal with the exception

First of all, coding an application using reflection is hard. A developer must have a strong grasp of the internal structure of the Java programming language, because the usage of reflection contains drawbacks and dangers, such as performance overhead and exposure of internal fields and methods.

If you decide to use reflection, consider enclosing your code inside a try-catch statement and manipulate the InvocationTargetException accordingly. Notice that the result of the getCause method can be one of the following:

In your application’s code, make sure that you check for all aforementioned cases, otherwise your code may produce undesired bugs.

Рекомендуем к прочтению

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

Ваш адрес email не будет опубликован.