Bout Sotirios-efstathios Maneassotirios-efstathios (stathis) Maneas are a postgraduate student at the Department of Informa Tics and telecommunications of the national and Kapodistrian University of Athens. His main interests include distributed systems, Web crawling, model checking, operating systems, programming languages and Web applications.java.lang.reflect.invocationtargetexception–how to handle invocation Target Exception
Posted By:sotirios-efstathios maneas in exceptions December 31st,
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of application s running in the Java Virtual machine. The reflection layer wraps any thrown exception as an InvocationTargetException
. In this to, it is clear whether the exception were actually caused by a failure on the reflection call, or a failure withi n the method called.
The is InvocationTargetException
a checked exception This 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 was known as the and cause
can be accessed via the getCause
method.
For more information on the reflection in Java, please refer to the page here
.
Error case
The following code snippet throws an InvocationTargetException
:
Reflectionexample.java:
1 Package Main.java;2 3 import java.lang.reflect.InvocationTargetException;4 5 import Java.lang.reflect.Method;6 7 8 Public classReflectionexample {9 Ten@SuppressWarnings ("Unused") One Private intTestMethod (String str) { A if(str.length () = =0) - Throw NewIllegalArgumentException ("The string must contain at least one character!"); -System. out. println ("Inside testmethod:argument ' s value equals to: \ ""+ str +"\""); the return 0; - } - Public Static voidMain (String ... args) { - Try { + - //Retrieve an instance of the current class as an Object. +class<?> C = Class.forName ("Main.java.ReflectionExample"); A atObject T =c.newinstance (); - -method[] Declaredmethods =c.getdeclaredmethods (); - - for(Method method:declaredmethods) { - inString MethodName =method.getname (); - to //Skip the current main method. + - if(Methodname.contains ("Main")) the * Continue; $ Panax NotoginsengSystem. out. Format ("invoking%s ()%n", methodName); - the Try { + A //Declare the method as accessible. the +Method.setaccessible (true); - $ $ - /*Invoke the method with a ' null ' parameter value, in order - the * For the exception to is thrown.*/ - WuyiObject returnvalue = Method.invoke (t,""); the - Wu -System. out. Format ("%s () returned:%d%n", MethodName, returnvalue); About $ } - - Catch(InvocationTargetException ex) { - ASystem.err.println ("An invocationtargetexception was caught!"); + theThrowable cause =ex.getcause (); - $System. out. Format ("invocation of%s failed because of:%s%n", the the MethodName, Cause.getmessage ()); the the } - in } the the } About Catch(ClassNotFoundException | instantiationexception |illegalaccessexception ex) { the theSystem.err.println ("The following exception was thrown:"); the + ex.printstacktrace (); - the }Bayi the } the -}
The result of the above snippet is:
1 invoking TestMethod ()
2 an invocationtargetexception was caught!
3 invocation of TestMethod failed because of:the string must contain at least one character!
If we carefully observe the code, we'll understand why the is InvocationTargetException
thrown. Initially, we get an instance of the ReflectionExample
class. Then, we iterate-it declared methods and we call the method under the name testMethod
, passing a empty String as an Argu ment.
However, the testMethod
throws an IllegalArgumentException
, with the length of the string equals to zero. That exception are wrapped as an and are thrown in our InvocationTargetException
sample application.
If We change the 39th line to:
" Hello from Java Code geeks! ");
The execution continues without any exception being thrown. As a result, we get the following result:
1 invoking TestMethod () 2 Inside testmethod:argument's value equals to: "Hello from Java Code geeks!" 3 4 0
How to deal with the exception
First of all, the coding an application using reflection are hard. A developer must has a strong grasp of the internal structure of the Java programming language, because the usage of REFL Ection 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
accord ingly. Notice that the result of the method can be one of the getCause
following:
- A null value.
- An unchecked exception, such as
RuntimeException
, IllegalArgumentException
, NullPointerException
, etc.
- A checked exception, such as
NameNotFoundException
, etc.
- A
java.lang.Error
, such as StackOverflowError
, OutOfMemoryError
etc.
In your application's code, make sure, the check for all aforementioned cases, otherwise your code may PROD UCE undesired bugs.
This is a tutorial about Java ' s InvocationTargetException
.
Tagged with:reflection
The essay comes from:http://examples.javacodegeeks.com/java-basics/exceptions/ java-lang-reflect-invocationtargetexception-how-to-handle-invocation-target-exception/
Java.lang.reflect.invocationtargetexception