Caused by java lang reflect invocationtargetexception android

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

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

Автор: baeldung
Дата записи

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 и как справиться с таким сценарием на простом примере.

Как обычно, код, используемый в этой статье, доступен на GitHub .

Источник

Invocation Target Exception Class

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

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

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Constructors

Constructs an InvocationTargetException with null as the target exception.

A constructor used when creating managed representations of JNI objects; called by the runtime.

Constructs an InvocationTargetException with null as the target exception.

Constructs an InvocationTargetException with null as the target exception.

Fields

Properties

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

(Inherited from Throwable) Class (Inherited from Throwable) Clause Handle

The handle to the underlying Android instance.

Читайте также:  Super vpn для android

(Inherited from Throwable) JniIdentityHashCode (Inherited from Throwable) JniPeerMembers LocalizedMessage

Creates a localized description of this throwable.

(Inherited from Throwable) Message

Returns the detail message string of this throwable.

(Inherited from Throwable) PeerReference (Inherited from Throwable) StackTrace (Inherited from Throwable) TargetException

Get the thrown target exception.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

This API supports the Mono for Android infrastructure and is not intended to be used directly from your code.

Methods

Appends the specified exception to the exceptions that were suppressed in order to deliver this exception.

(Inherited from Throwable) Dispose() (Inherited from Throwable) Dispose(Boolean) (Inherited from Throwable) FillInStackTrace()

Fills in the execution stack trace.

(Inherited from Throwable) GetStackTrace()

Provides programmatic access to the stack trace information printed by #printStackTrace() .

(Inherited from Throwable) GetSuppressed()

Returns an array containing all of the exceptions that were suppressed, typically by the try -with-resources statement, in order to deliver this exception.

(Inherited from Throwable) InitCause(Throwable)

Initializes the cause of this throwable to the specified value.

(Inherited from Throwable) PrintStackTrace()

Prints this throwable and its backtrace to the standard error stream.

(Inherited from Throwable) PrintStackTrace(PrintStream)

Prints this throwable and its backtrace to the standard error stream.

(Inherited from Throwable) PrintStackTrace(PrintWriter)

Prints this throwable and its backtrace to the standard error stream.

(Inherited from Throwable) SetHandle(IntPtr, JniHandleOwnership)

Sets the Handle property.

(Inherited from Throwable) SetStackTrace(StackTraceElement[])

Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.

(Inherited from Throwable) ToString() (Inherited from Throwable) UnregisterFromRuntime() (Inherited from Throwable)

Explicit Interface Implementations

IJavaPeerable.Disposed() (Inherited from Throwable)
IJavaPeerable.DisposeUnlessReferenced() (Inherited from Throwable)
IJavaPeerable.Finalized() (Inherited from Throwable)
IJavaPeerable.JniManagedPeerState (Inherited from Throwable)
IJavaPeerable.SetJniIdentityHashCode(Int32) (Inherited from Throwable)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates) (Inherited from Throwable)
IJavaPeerable.SetPeerReference(JniObjectReference) (Inherited from Throwable)

Extension Methods

Performs an Android runtime-checked type conversion.

Источник

Java Exception Handling – InvocationTargetException

Moving along through our in-depth Java Exception Handling series, today we’ll take a closer look at the java.lang.reflect.InvocationTargetException. The java.lang.reflect.InvocationTargetException is thrown when working with the reflection API while attempting to invoke a method that throws an underlying exception itself.

In this article we’ll explore the InvocationTargetException in more detail by looking at where it resides in the Java Exception Hierarchy. We’ll also dig into a few functional reflection code samples that will illustrate how java.lang.reflect.InvocationTargetExceptions are typically thrown, showing how you might handle them in your own code, so let’s get crackin’!

The Technical Rundown

  • All Java errors implement the java.lang.Throwable interface, or are extended from another inherited class therein.
  • java.lang.Exception inherits from java.lang.Throwable .
  • java.lang.ReflectiveOperationException inherits from java.lang.Exception .
  • Finally, java.lang.reflect.InvocationTargetException inherits from java.lang.ReflectiveOperationException .

When Should You Use It?

Since the InvocationTargetException deals with reflection, let’s briefly talk a bit about that practice and why explicitly invoking a method via reflection might be useful. In the most basic sense, reflection allows the JVM and your underlying code to inspect classes, methods, interfaces, and the like during runtime, without having directly called or identified those objects during compilation. This powerful capability means that your code can find classes and invoke methods that it wasn’t originally designed to handle out of the box.

Читайте также:  Образы дисков для андроид

To illustrate how invocation in Java works we have a few basic examples. To keep things simple, we’ll start with the full working code sample below, after which we’ll break it down in more detail to see what’s really going on:

As briefly mentioned in the introduction, an InvocationTargetException is automatically generated by reflection-related objects, and wraps (or attaches) itself to the underlying, actual exception type that caused the problem. This occurs when calling the java.lang.reflect.Method.invoke() method, where that invocation target method throws an exception.

To illustrate the issue we’ve got a basic Book class with a few property getter/setter methods, along with a some extraneous methods ( getTagline() and throwException() ) that we’ll explicitly call in the rest of our code:

The invokeGetTaglineMethod() method shows a basic, working example of using Java reflection to invoke() a class instance method ( Book.getTagline() , in this case).

The comments explain most everything that we’re doing, but the basic idea is that we starting by creating a Book instance object of book . We then need to instantiate a Class object, so we get a reflection of io.airbrake.Book , from which we can retrieve the declared getTagline() method. Using that Method instance of getTagline() we’re able to invoke() the method. Since this is an instance method, we need to pass an instance of the object as the first argument, so this is where we use the book object that was created at the beginning.

Executing this code results in the book object output, followed by the output from calling getTagline.invoke(book) , as expected:

Now that we’ve seen how invocation works, let’s try invoking a different Book instance method, specifically the Book.throwException() method. As its name suggests, Book.throwException() merely throws an Exception , using the passed String argument for the message:

To test this we’ll execute the invokeThrowExceptionMethod() method, which performs almost exactly the same code as our previous example, except the calls to getDeclaredMethod() and invoke() differ slightly since we’re also passing arguments to the invoked method:

Since the Book.throwException() method we’re invoking explicitly throws an error, our expectation is that executing the above code will result in a java.lang.reflect.InvocationTargetException being thrown. Sure enough, that’s exactly what happens:

Normally we’d only catch the parent InvocationTargetException in this scenario, which indicates the it was «Caused by: java.lang.Exception . » . However, a Throwable object implements the getCause() method, which returns the causal exception (if applicable). In the case of a InvocationTargetException instance, the cause is always the underlying exception object that occurred inside the invoked method, so checking for a cause when catching such exceptions is a good idea.

The Airbrake-Java library provides real-time error monitoring and automatic exception reporting for all your Java-based projects. Tight integration with Airbrake’s state of the art web dashboard ensures that Airbrake-Java gives you round-the-clock status updates on your application’s health and error rates. Airbrake-Java easily integrates with all the latest Java frameworks and platforms like Spring , Maven , log4j , Struts , Kotlin , Grails , Groovy , and many more. Plus, Airbrake-Java allows you to easily customize exception parameters and gives you full, configurable filter capabilities so you only gather the errors that matter most.

Читайте также:  Android emulator and google play

Check out all the amazing features Airbrake-Java has to offer and see for yourself why so many of the world’s best engineering teams are using Airbrake to revolutionize their exception handling practices! Try Airbrake free for 30 days.

Monitor Your App Free for 30 Days

Discover the power of Airbrake by starting a free 30-day trial of Airbrake. Quick sign-up, no credit card required. Get started.

Источник

Что может вызвать Java.ленг.отражать.InvocationTargetException?

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

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

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

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

13 ответов

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

просто разверните причину в InvocationTargetException и вы получите оригинальный.

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

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

использовать getCause() метод InvocationTargetException для получения исходного исключения.

из Javadoc метода.invoke ()

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

это исключение вызывается, если вызванный метод вызвал исключение.

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

это InvocationTargetException вероятно, завершает ваш ArrayIndexOutOfBoundsException . При использовании отражения невозможно заранее сказать, что этот метод может бросить , поэтому вместо использования throws Exception подход, все исключения пойманы и завернуты в InvocationTargetException .

этой описывает что-то вроде

InvocationTargetException является проверенным исключением, которое обертывает исключение, создаваемое вызываемым методом или конструктором. С момента выпуска 1.4, данное исключение было модифицировано в соответствии с механизмом цепочки исключений общего назначения. «Целевое исключение», которое при строительстве и доступ к ней через метод getTargetException () теперь известен как причина и может быть доступ через Перекидным.метод getCause (), а также вышеупомянутый » устаревший метод.»

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

Я java.lang.reflect.InvocationTargetException ошибка из оператора, вызывающего объект регистратора во внешнем class внутри try / catch заблокировать в моем class .

шагая через код в отладчике Eclipse и наведя курсор мыши на оператор logger, я увидел logger object был null (некоторые внешние константы должны быть созданы в самом верху моего class ).

это исключение возникает, если базовый метод (метод, называемый с помощью отражения) создает исключение.

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

Я столкнулся с той же проблемой. Я использовал е.getCause().getCause () затем я обнаружил, что это из-за неправильных параметров, которые я передавал. Было исключение nullPointerException при получении значения одного из параметров. Надеюсь, это поможет вам.

Источник

Оцените статью