Меню

Java lang reflect invocationtargetexception ошибка причина

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

try{
    method.invoke();
} catch(InvocationTargetException ite) {
    throw ite.getCause();
} catch(Exception e) {
    // handle non-reflection originated exceptions
    throw e;
}

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.

Overview

Exception Handling is one of the most powerful mechanisms in Java. It is used to handle the runtime errors during execution so that in case of an error, you can prevent the program from crashing and the flow of the application can remain uninterrupted despite the error.

If you have ever worked with Java Reflection API, you must have at least once encountered the java.lang.reflect.InvocationTargetException in your program. In this article, we will be understanding the InvocationTargetException, the reasons behind its occurrence, and how to properly handle it. The article also includes some appropriate examples for your ease.

explore new Java roles

What is Java reflection?

Just for starters, Reflection is a feature in Java that allows a Java program to examine itself and manipulate the internal properties of the program during execution.

For instance, it is allowed for a Java class to obtain the names of all its members and display them while executing.

This feature to examine and manipulate a Java class from within itself may not seem to be a big thing and feels like a common feature, but surprisingly this feature does not exist in various renowned programming languages nor there is any alternative for it.

For instance, Cor C++ programmers have no possible way to obtain information about the functions defined within their program.

Java reflection offers some very significant uses, especially in JavaBeans, where software components can be tweaked visually using a builder tool.

The tool makes use of reflection to obtain the properties of the Java class when they are dynamically loaded.

See this code below demonstrating a simple example of using reflection

1.  import java.lang.reflect.*;
2. 
3.    public class DumpMethods {
4.      public static void main(String args[])
5.    {
6.      try {
7.         Class myClass = Class.forName(args[0]);
8.         Method m[] = myClass.getDeclaredMethods();
9.         for (int i = 0; i < m.length; i++)
10.        System.out.println(m[i].toString());
11.   }
12.     catch (Throwable e) {
13.     System.err.println(e);
14.      }
15.    }
16. }

 This code snipped is for the invocation of:

java DumpMethods java.util.Stack

And the output is:

public java.lang.Object java.util.Stack.push(
    java.lang.Object)
   public synchronized
     java.lang.Object java.util.Stack.pop()
   public synchronized
      java.lang.Object java.util.Stack.peek()
   public boolean java.util.Stack.empty()
   public synchronized
     int java.util.Stack.search(java.lang.Object)

The output list down the names of all methods of class java.util.Stack, along with their fully qualified parameter and return types.

The InvocationTargetException is not the actual exception we have to deal with instead it is a checked exception that wraps the actual exception thrown by an invoked method or constructor. As of the release of JDK 2.4, this exception has been modified enough to be used as a  general-purpose exception-chaining mechanism.

There have been some changes since the beginning as the “target exception” that is provided at the time of construction and is accessed through the getTargetException() method is now known as the cause method, and can be accessed via the Throwable.getCause() method, but the previously mentioned legacy method is also still applicable.

See this example of a java.lang.reflect.InvocationTargetException thrown when a method that is called using Method.invoke() throws an exception:

1. import java.lang.reflect.InvocationTargetException;
2. import java.lang.reflect.Method;
3. 
4. public class InvocationTargetExceptionDemo {
5.    public int dividedByZero() {
6.         return 1 / 0;
7.     }
8. 
9.     public static void main(String[] args) throws NoSuchMethodException, 
       IllegalAccessException {
10.       InvocationTargetExceptionDemo invoked = new InvocationTargetExceptionDemo(); 
11.       Method method = InvocationTargetExceptionDemo.class.getMethod("divisionByZero");
12.      try {
13.      method.invoke(invoked);
14.     } catch (InvocationTargetException e) {
15.       e.printStackTrace();
16.    }
17.    }
18.  }

In this example, the main() method invokes the dividedByZero() method using Method.invoke(). As dividedByZero() method will throw an ArithmeticException, it will be wrapped within an InvocationTargetException thrown in the main() method.

The output error is as shown:

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:564)
    at InvocationTargetExceptionDemo.main(InvocationTargetExceptionDemo.java:13)
Caused by: java.lang.ArithmeticException: / by zero
    at InvocationTargetExceptionDemo.dividedByZero(InvocationTargetExceptionDemo.java:6)
    ... 5 more

As discussed earlier, the above mentioned code snippet along with its output has made it clear that the actual exception is the ArithmeticException and it got wrapped into an InvocationTargetException.

Now, the question that must come to your mind is why the reflection does not directly throw the actual exception instead of wrapping it into an InvocationTargetException? Why do we even need it? The reason is clear. It allows the programmer to first understand whether the exception has occurred due to some sort of failure in properly calling the method through the reflection layer or whether the exception has occurred within the method itself.

What causes java.lang.reflect.InvocationTargetException?

The java.lang.reflect.InvocationTargetException mainly occurs while working with the reflection layer. When you attempt to invoke a method or constructor and it throws an underlying exception, that underlying exception is the actual cause of the occurrence of java.lang.reflect.InvocationTargetException. The reflection layer wraps the actual exception thrown by the method with the InvocationTargetException thus you get the java.lang.reflect.InvocationTargetException in return.

How to handle with java.lang.reflect.InvocationTargetException?

To properly deal with the InvocationTargetException, you have to handle the actual underlying exception that is the main reason for InvocationTargetException. To cater to that, the Throwable.getCause() method is used to get more information about the exception such as the type of exception, after invocation. This information is undoubtedly very useful for resolving the java.lang.reflect.InvocationTargetException.

Consider the below example, it is an extension to the previous code example which intentionally generated an exception (divided by zero) in the method InvocationTargetExceptionDemo:

1. import java.lang.reflect.Method; 
2. public class TestInvocationException { 
3.      public static void main(String[] args) { 
4.       InvocationDemo id = new InvocationDemo(); 
5.        ¬¬¬¬¬¬// Getting Access to all the methods of myInvocation Class: 
6.    Method[] m = InvocationDemo.class.getMethods(); 
7.   try { 
8.   // First method of the myInvocatio Class is invoked here 
9.   m[0].invoke(id); 
10.     } 
11.    catch(Exception e) { 
12.      // wrapper exception: 
13.     System.out.println("Wrapper exception: " + e); 
14.     // getCause method is used with the actual exception: 
15.      System.out.println("Underlying exception: " + e.getCause()); 
16.    } 
17.   } 
18.  } 
19. 
20.    class myInvocation{ 
21.      public void InvocationTargetExceptionDemo() { 
22.        // Dividing by zero again 
23.        System.out.println(3 / 0); 
24.     } 
25. }

Output generated from the getCause() method is shown below, it clearly states the type of underlying exception:

Wrapper exception: java.lang.reflect.InvocationTargetException

Underlying exception: java.lang.ArithmeticException: / by zero

Here, the getCause() method is used with the same exception object that was thrown and it is identified  that ArithmeticException.class is the cause of the InvocationTargetException.

Now, it may seem very easy as programmers can easily identify the divided by zero error from the code and exception for it may be already known but suppose you are dealing with any other exception and your code is significantly longer and more complex, just the name of the exception from the getCause() method can come in very handy.

Also Read: How to use Java Generic Interface

So, once you get the reason behind the underlying exception, you can also re-throw the same exception, you can also wrap it in some custom exception, or you can also log the exception based on your requirement.

Conclusion

Exceptions are the best way to deal with errors in any programming language. Proper knowledge of exceptions and their dealing can be a lifesaver for a Java coder on many occasions.

In this comprehensive article, we have explored the java.lang.reflect.invocationtargetException.

We discussed how the reflection layer wraps an underlying exception in Java. To be precise, when we invoke a class using the Method.invoke(), and if it throws an exception; it will be wrapped by the java.lang.reflect.InvocationTargetException class.­ We have also seen how to determine the underlying reason behind the occurrence of InvocationTargetException and how to handle such a problem in your Java code.

new Java jobs

Проблемы

Рассмотрим следующий сценарий.

  • На компьютере установить следующее программное обеспечение:

    • Eclipse 3.5 Eclipse 3.6 или продукта, который основан на одной из этих версий.

    • Командный обозреватель Microsoft Visual Studio везде 2010 Пакет обновления 1 (SP1) для Eclipse

    • Windows Internet Explorer 9

  • Командный обозреватель везде 2010 используйте для подключения к серверу Microsoft Team Foundation Server (TFS).

  • При попытке сохранить или просмотреть рабочий элемент, содержащий несколько элементов управления HTML.

В этом случае, сохранить или просмотреть завершится неудачно. Кроме того, появляется приведенное ниже сообщение об ошибке:

Сохранить FailedJava.lang.reflect.InvocationTargetException

Причина

Эта проблема возникает из-за изменения в механизме JavaScript, появившееся в Internet Explorer 9. Изменение конфликтует вызывающего кода в уязвимых версиях Eclipse. Этот конфликт приводит к failaure функции для рабочего элемента, содержащий заполнены в командный обозреватель везде 2010 с пакетом обновления 1 элемент управления текстом в формате RTF. Таким образом сообщение об ошибке всплывает.

Решение

Сведения об исправлении

Исправление доступно для загрузки на следующий веб-узел центра загрузки корпорации Майкрософт:Download загрузить исправление. Дополнительные сведения о том, как загрузить файлы поддержки Майкрософт щелкните следующий номер статьи базы знаний Майкрософт:

119591 Как загрузить файлы технической поддержки Майкрософт через веб-службы Этот файл был проверен корпорацией Майкрософт на наличие вирусов. Корпорация Майкрософт использует самые последние на момент публикации файла версии антивирусного программного обеспечения. Файл хранится на защищенных серверах, что предотвращает его несанкционированное изменение. Примечание. Чтобы установить данное исправление, выполните следующие действия.

  1. Сохраните файл Tfseclipseplugin-updatesitearchive-10.1.0-qfe1.zip пакета исправлений в локальной папке.

  2. Запустите Eclipse.

  3. В меню Справка выберите пункт Установки нового программного обеспечения.

  4. Нажмите кнопку Добавить.

  5. В поле имя введите подключаемый модуль архивации локальной командный обозреватель и нажмите кнопку Архивировать.

  6. Выберите файл Tfseclipseplugin-updatesitearchive-10.1.0-qfe1.zip, который был сохранен в локальной папке и нажмите кнопку ОК.

  7. В диалоговом окне установки выберите установите флажок, соответствующий командный обозреватель везде в списке функций.

  8. Два раза нажмите кнопку Далее .

  9. Принять условия лицензионного соглашения на использование программного обеспечения корпорации Майкрософт, а затем нажмите кнопку Далее.

  10. Нажмите кнопку Завершить.

Дополнительные сведения об установке подключаемого модуля Team Foundation Server и клиентом командной строки загрузить и просмотреть веб-страницу Майкрософт:

Установка подключаемого модуля Team Foundation Server и клиентом командной строки

Предварительные условия

Для установки этого исправления необходимо иметь Microsoft Visual Studio командный обозреватель везде 2010 на компьютере установлен Пакет обновления 1 (SP1).

Необходимость перезагрузки

После установки этого исправления необходимо перезапустить Eclipse.

Сведения о замене исправлений

Это исправление не заменяет ранее выпущенные исправления.

Сведения о файлах

Глобальная версия этого исправления содержит атрибуты файла (или более поздние атрибуты файлов), приведенные в следующей таблице. Дата и время для файлов указаны в формате UTC. При просмотре сведений о файлах выполняется перевод соответствующих значений в местное время. Чтобы узнать разницу между временем UTC и местным временем, откройте вкладку Часовой пояс элемента Дата и время панели управления.

Имя файла

Версия файла

Размер

дата

Время

Tfseclipseplugin-updatesitearchive-10.1.0-qfe1.zip

Not Applicable

12,854,618

24-May-2011

07:17

Обходной путь

Чтобы обойти эту проблему, выполните указанные ниже действия.

  1. Откройте папку программы Eclipse.

  2. Найдите и откройте Eclipse.ini в текстовом редакторе. Например откройте файл с помощью блокнота.

  3. Добавьте в конец файла следующую строку:

    -Dcom.microsoft.tfs.client.common.ui.controls.generic.html.htmleditor.disable=

  4. Сохраните файл Eclipse.ini и перезагрузите Eclipse.

Статус

Корпорация Майкрософт подтверждает наличие этой проблемы в своих продуктах, которые перечислены в разделе «Применяется к».

Нужна дополнительная помощь?

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

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

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.

package org.arpit.java2blog;

public class StringUtils {

    public int getLengthOfString(String str)

    {

        return str.length();

    }

}

Create anther class to call getLengthOfString using reflection.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

package org.arpit.java2blog;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class ReflectionMain {

    public static void main(String[] args) {

        StringUtils su=new StringUtils();

        try {

            Class[] paramString = new Class[1];

            paramString[0] = String.class;

            Method method=StringUtils.class.getMethod(«getLengthOfString»,paramString);

            String str=null;

            Object len = method.invoke(su, str);

            System.out.println(len);

        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {

            e.printStackTrace();

        }

    }

}

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

package org.arpit.java2blog;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class ReflectionMain {

    public static void main(String[] args) {

        StringUtils su=new StringUtils();

        try {

            Class[] paramString = new Class[1];

            paramString[0] = String.class;

            Method method=StringUtils.class.getMethod(«getLengthOfString»,paramString);

            String str=null;

            Object len = method.invoke(su, str);

            System.out.println(len);

        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {

            Throwable actualException = e.getCause();

            actualException.printStackTrace();

        }

    }

}

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.

package org.arpit.java2blog;

public class StringUtils {

    public int getLengthOfString(String str) {

        if (str != null) {

            return str.length();

        } else

            return 0;

    }

}

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

0

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

If a InvocationTargetException is a checked exception in Java that wraps an exception thrown by an invoked method or constructor. The method or constructor that throws the exception is invoked using the Method.invoke() method. The InvocationTargetException is quite common when using the Java Reflection API.

The Java reflection layer wraps any exception as an InvocationTargetException. This helps clarify whether the exception is caused by an issue in the reflection call or within the called method.

What Causes InvocationTargetException

The InvocationTargetException occurs mainly when working with the Java reflection API to invoke a method or constructor, which throws an exception.

This underlying exception is the actual cause of the issue, therefore resolving the InvocationTargetException equates to finding and resolving the underlying exception that occurs within the invoked method.

InvocationTargetException Example

Here is an example of a InvocationTargetException thrown when a method that is called using Method.invoke() throws an exception:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class InvocationTargetExceptionExample {
    public int divideByZero() {
                return 1 / 0;
        }

    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException {
        InvocationTargetExceptionExample itee = new InvocationTargetExceptionExample(); 
        Method method = InvocationTargetExceptionExample.class.getMethod("divideByZero");
        try {
            method.invoke(itee);
        } catch (InvocationTargetException ite) {
            ite.printStackTrace();
        }
        }
}

In this example, the main() method invokes divideByZero() using Method.invoke(). Since divideByZero() throws an ArithmeticException, it is wrapped within an InvocationTargetException thrown in the main() method:

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:564)
    at InvocationTargetExceptionExample.main(InvocationTargetExceptionExample.java:13)
Caused by: java.lang.ArithmeticException: / by zero
    at InvocationTargetExceptionExample.divideByZero(InvocationTargetExceptionExample.java:6)
    ... 5 more

How to Resolve InvocationTargetException

Since the underlying exception is the actual cause of the InvocationTargetException, finding and resolving the underlying exception resolves the InvocationTargetException. The getCause() method of the Throwable class can be used to obtain the underlying exception. The earlier example can be updated accordingly to get the underlying exception and print its stack trace:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class InvocationTargetExceptionExample {
    public int divideByZero() {
        return 1 / 0;
    }

    public static void main(String[] args) throws NoSuchMethodException {
        InvocationTargetExceptionExample itee = new InvocationTargetExceptionExample();
        Method method = InvocationTargetExceptionExample.class.getMethod("divideByZero");
        try {
            method.invoke(itee);
        } catch (InvocationTargetException ite) {
            Throwable underlyingException = ite.getCause();
            underlyingException.printStackTrace();
        } catch (IllegalAccessException iae) {
            iae.printStackTrace();
        }
    }
}

Running the above will print out the stack trace of the underlying ArithmeticException:

java.lang.ArithmeticException: / by zero
    at InvocationTargetExceptionExample.divideByZero(InvocationTargetExceptionExample.java:6)
    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:564)
    at InvocationTargetExceptionExample.main(InvocationTargetExceptionExample.java:13)

The stack trace can then be inspected to resolve the underlying exception. This will also resolve the wrapped InvocationTargetException.

Track, Analyze and Manage Java Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates Java error monitoring and triaging, making fixing errors easier than ever. Try it today.


public

class
InvocationTargetException

extends ReflectiveOperationException

java.lang.Object
   ↳ java.lang.Throwable
     ↳ java.lang.Exception
       ↳ java.lang.ReflectiveOperationException
         ↳ java.lang.reflect.InvocationTargetException


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.»

Summary

Public constructors


InvocationTargetException(Throwable target)

Constructs a InvocationTargetException with a target exception.


InvocationTargetException(Throwable target, String s)

Constructs a InvocationTargetException with a target exception
and a detail message.

Protected constructors


InvocationTargetException()

Constructs an InvocationTargetException with
null as the target exception.

Public methods

Throwable


getCause()

Returns the cause of this exception (the thrown target exception,
which may be null).

Throwable


getTargetException()

Get the thrown target exception.

Inherited methods

From class

java.lang.Throwable


final

void


addSuppressed(Throwable exception)

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

Throwable


fillInStackTrace()

Fills in the execution stack trace.

Throwable


getCause()

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

String


getLocalizedMessage()

Creates a localized description of this throwable.

String


getMessage()

Returns the detail message string of this throwable.

StackTraceElement[]


getStackTrace()

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

final

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.

Throwable


initCause(Throwable cause)

Initializes the cause of this throwable to the specified value.

void


printStackTrace()

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

void


printStackTrace(PrintWriter s)

Prints this throwable and its backtrace to the specified
print writer.

void


printStackTrace(PrintStream s)

Prints this throwable and its backtrace to the specified print stream.

void


setStackTrace(StackTraceElement[] stackTrace)

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

String


toString()

Returns a short description of this throwable.

From class

java.lang.Object


Object


clone()

Creates and returns a copy of this object.

boolean


equals(Object obj)

Indicates whether some other object is «equal to» this one.

void


finalize()

Called by the garbage collector on an object when garbage collection
determines that there are no more references to the object.

final

Class<?>


getClass()

Returns the runtime class of this Object.

int


hashCode()

Returns a hash code value for the object.

final

void


notify()

Wakes up a single thread that is waiting on this object’s
monitor.

final

void


notifyAll()

Wakes up all threads that are waiting on this object’s monitor.

String


toString()

Returns a string representation of the object.

final

void


wait(long timeout, int nanos)

Causes the current thread to wait until another thread invokes the
notify() method or the
notifyAll() method for this object, or
some other thread interrupts the current thread, or a certain
amount of real time has elapsed.

final

void


wait(long timeout)

Causes the current thread to wait until either another thread invokes the
notify() method or the
notifyAll() method for this object, or a
specified amount of time has elapsed.

final

void


wait()

Causes the current thread to wait until another thread invokes the
notify() method or the
notifyAll() method for this object.

Public constructors

InvocationTargetException

public InvocationTargetException (Throwable target)

Constructs a InvocationTargetException with a target exception.

Parameters
target Throwable: the target exception

InvocationTargetException

public InvocationTargetException (Throwable target, 
                String s)

Constructs a InvocationTargetException with a target exception
and a detail message.

Parameters
target Throwable: the target exception
s String: the detail message

Protected constructors

InvocationTargetException

protected InvocationTargetException ()

Constructs an InvocationTargetException with
null as the target exception.

Public methods

getCause

public Throwable getCause ()

Returns the cause of this exception (the thrown target exception,
which may be null).

Returns
Throwable the cause of this exception.

getTargetException

public Throwable getTargetException ()

Get the thrown target exception.

This method predates the general-purpose exception chaining facility.
The Throwable#getCause() method is now the preferred means of
obtaining this information.

Returns
Throwable the thrown target exception (cause of this exception).

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

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

 try{
 ..
 m.invoke(testObject);
 ..
 } catch(AssertionError e){
 ...
 } catch(Exception e){
 ..
 }

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

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

16 май 2011, в 19:09

Поделиться

Источник

13 ответов

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

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

Jon Skeet
16 май 2011, в 17:38

Поделиться

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

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

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

Andreas_D
16 май 2011, в 18:22

Поделиться

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

Daniel Ward
30 июнь 2012, в 19:28

Поделиться

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

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

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

Peter Lawrey
16 май 2011, в 18:49

Поделиться

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

try {

    // try code
    ..
    m.invoke(testObject);
    ..

} catch (InvocationTargetException e) {

    // Answer:
    e.getCause().printStackTrace();
} catch (Exception e) {

    // generic exception handling
    e.printStackTrace();
}

Rocky Inde
23 дек. 2014, в 00:01

Поделиться

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

Liv
16 май 2011, в 17:13

Поделиться

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

try{
  ...
} catch(Exception e){
   if(e.getCause().getClass().equals(AssertionError.class)){
      // handle your exception  1
   } else {
      // handle the rest of the world exception 
   }
} 

Mehdi
09 нояб. 2016, в 16:13

Поделиться

В этом описывается что-то вроде

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

Sazzad Hissain Khan
11 дек. 2013, в 17:40

Поделиться

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

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

Stuart Cardall
14 дек. 2017, в 10:56

Поделиться

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

Deepak Vajpayee
17 июнь 2017, в 19:39

Поделиться

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

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

Nikhil Kumar
05 нояб. 2014, в 10:55

Поделиться

  • Перечислить все файлы jar из режима Eclipse Navigator
  • Убедитесь, что все файлы jar находятся в двоичном режиме.

Manik
09 нояб. 2012, в 09:28

Поделиться

Ошибка исчезла после того, как я сделал
Очистить- > Запустить xDoclet- > Запустить xPackaging.

В моей рабочей области, в ecllipse.

Ashutosh Singh
02 май 2016, в 15:16

Поделиться

Ещё вопросы

  • 1ushort Операции Throwing Int Cast Ошибки
  • 0Минимальный веб-редактор для приложений Rails
  • 1C # диаграмма класса — пользовательские метки для оси х?
  • 0Почему этот код не возвращает 0?
  • 1ошибка установки pip «Microsoft Visual C ++ 14.0 требуется.»
  • 0Нужна помощь в понимании параметров конструктора и статических переменных
  • 0условный оператор ELEMENT, содержащий jQuery
  • 0Запрос базы данных MYSQL с использованием PDO на основе первого значения другой таблицы
  • 0Удалить тег комментария из ответа POST
  • 0Div выберите выпадающее меню JQuery переключатель и параметр
  • 1Панды — изменение каждой даты в столбце даты [дубликаты]
  • 1JAVA Назначение целого числа из readFile в 2-мерный массив
  • 1Строка заголовка появилась снова после возвращения в моем приложении
  • 0Извлечение JSON из неизвестного ключа массива
  • 0MySQL SELECT, объединенные таблицы и группы / счетчики COMMA разделены значения
  • 1перемещение поля в новый столбец, если оно содержит значение в определенном столбце
  • 0Проблема с jQuery-слайдом
  • 0Новые столбцы для случайных случаев: новые столбцы или отдельная таблица или столбец json
  • 0Ошибка компоновщика SDL 2
  • 0Используйте форму проверки JavaScript только тогда, когда браузер не может проверить форму
  • 0Visual Studio 2017 не может загрузить базу данных MySQL
  • 0Google Feed API получить 10 записей одновременно загрузить больше с следующий
  • 1объединение двух списков python с логической маской [duplicate]
  • 0Как включить медленный журнал запросов для движка Amazon «Aurora MySQL»?
  • 0есть ли вообще поменять цвет фона флажка?
  • 0отправка данных на сервер с использованием сервисов и контроллеров
  • 1default.properties не создается
  • 0Поиск комбинации возврата каретки / перевода строки с помощью c ++
  • 0JQuery рекурсивно проверено
  • 0Изменить цвет фона CSS с помощью jQuery
  • 0Как получить доступ к переменной метки в QMessageBoxPrivate при расширении класса QMessageBox?
  • 1Конструктор `QImage` имеет неизвестное ключевое слово` data`
  • 1Как бы я отсортировал список строк по целым числам в этой строке? *Ява*
  • 1Совместное использование Android NDK Lib
  • 0Вызов переменной javascript внутри кода ac #
  • 0Mysql: я хочу сравнить результаты двух запросов и вернуть результаты
  • 0Подключение от парусов в ec2 к mysql в rds дает ошибку тайм-аута неактивного рукопожатия
  • 1Событие инициализации страницы framework7 не срабатывает
  • 1Почему я не могу заставить эти расширения работать?
  • 0Редактировать текстовый файл в C ++
  • 0Symfony, Doctrine, merge не работают должным образом (в то время как сохраняются те же сущности)
  • 0Настройка основных параметров Netbeans
  • 0MySQL Исключить сверх Включить в FIND_IN_SET ()
  • 1Как включить объект, который имеет общее свойство списка и свойство ссылочного типа в dapper?
  • 0Добавить текст в начале определенной строки в PHP
  • 1Android-будильник
  • 1Затмение андроида устройства исчезают
  • 0Как изменить форму легенды в Google-чартах?
  • 0Как я могу сказать mysql строку подключения через часовой пояс?
  • 0Перехватчик с ограниченным ответом для заголовков

Сообщество Overcoder

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Iw4sp exe ошибка приложения 0xc0000142
  • Iw3sp exe call of duty 4 ошибка что делать windows 10