i ran into following error an cannot find an solution.
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
> java.lang.reflect.InvocationTargetException (no error message)
I cannot say, what I have done last time, probably there is some library causing this error which i had updated.
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-parcelize'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
id 'androidx.navigation.safeargs.kotlin'
}
android {
compileSdkVersion rootProject.compileSdkVersion
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.padder.application"
minSdkVersion rootProject.minSdkVersion
targetSdkVersion rootProject.targetSdkVersion
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
buildFeatures {
viewBinding true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
freeCompilerArgs += "-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi"
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
implementation "androidx.core:core-ktx:$ktxVersion"
implementation "androidx.appcompat:appcompat:$appCompatVersion"
implementation "com.google.android.material:material:$materialVersion"
implementation "androidx.constraintlayout:constraintlayout:$constraintLayoutVersion"
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$testExtJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$espressoVersion"
// Fragment
implementation "androidx.fragment:fragment-ktx:$fragmentVersion"
// Navigation Component
implementation "androidx.navigation:navigation-fragment-ktx:$navigationVersion"
implementation "androidx.navigation:navigation-ui-ktx:$navigationVersion"
// Lifecycle + ViewModel & LiveData
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycleVersion"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycleVersion"
implementation "android.arch.lifecycle:common-java8:$lifecycleVersion"
// Coroutines
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutinesVersion"
// DataStore
implementation "androidx.datastore:datastore-preferences:$dataStoreVersion"
// Room
implementation "androidx.room:room-runtime:$roomVersion"
kapt "androidx.room:room-compiler:$roomVersion"
implementation "androidx.room:room-ktx:$roomVersion"
// Dagger Hilt
implementation "com.google.dagger:hilt-android:$hiltVersion"
kapt "com.google.dagger:hilt-android-compiler:$hiltVersion"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:$hiltAndroidXVersion"
kapt "androidx.hilt:hilt-compiler:$hiltAndroidXVersion"
}
kapt {
correctErrorTypes true
}
These are my librarys + versions. Hopefully this helps. I give you the full error log as well, so you have, what I have.
Executing tasks: [:app:assembleDebug] in project C:UsersNutzerDesktopIntelliJ_ProjectsApplication
> Task :app:preBuild UP-TO-DATE
> Task :app:preDebugBuild UP-TO-DATE
> Task :app:compileDebugAidl NO-SOURCE
[TASKS]
> Task :app:stripDebugDebugSymbols NO-SOURCE
> Task :app:validateSigningDebug UP-TO-DATE ^
> Task :app:kaptDebugKotlin FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
> java.lang.reflect.InvocationTargetException (no error message)
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 28s
21 actionable tasks: 2 executed, 19 up-to-date
Because inside the error is the Database mentioned, I give it as well.
package com.padder.application.data
import androidx.room.Database
import androidx.room.RoomDatabase
import javax.inject.Inject
@Database(entities = [Table1::class , Table2::class], version = 1) //exportSchema = false is not working
abstract class Database : RoomDatabase() {
abstract fun dao(): Dao
}
Just say if you need more snippeds, but hopefully these arent to much snippets that you not run away.
As wished here is the Dao I use:
package com.padder.application.data
import androidx.room.*
import kotlinx.coroutines.flow.Flow
@Dao
interface Dao {
/**
* SQL-Sort
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(item: Item)
@Update
suspend fun update(item: item)
@Delete
suspend fun delete(item: Item)
// Searchqueries LIST-Fragment
fun getItemList(sortState: SortSpinnerState, item: String, search: String) : Flow<List<Item>> =
when (sortState) {
SortSpinnerState.BY_NAME -> getItemListSortName(item, search)
SortSpinnerState.BY_TASTE -> getItemListSortTaste(item, search)
SortSpinnerState.BY_FAV -> getItemListSortFav(item, search)
SortSpinnerState.BY_LIKE -> getItemListSortLike(item, search)
}
@Query("SELECT nr, name, taste, marke, mag, fav FROM tabak WHERE marke = :marke AND name LIKE '%' || :search || '%' ORDER BY name ASC")
fun getItemListSortName(marke: String, search: String): Flow<List<Item>>
@Query("SELECT nr, name, taste, marke, mag, fav FROM tabak WHERE marke = :marke AND name LIKE '%' || :search || '%' ORDER BY taste ASC")
fun getItemListSortTaste(marke: String, search: String): Flow<List<Item>>
@Query("SELECT nr, name, taste, marke, mag, fav FROM tabak WHERE marke = :marke AND name LIKE '%' || :search || '%' ORDER BY fav = 1 DESC, name ASC")
fun getItemListSortFav(marke: String, search: String): Flow<List<Item>>
@Query("SELECT nr, name, taste, marke, mag, fav FROM tabak WHERE marke = :marke AND name LIKE '%' || :search || '%' ORDER BY like = 1 DESC, like = 2 DESC, like = 3 ASC, name ASC")
fun getItemListSortLike(marke: String, search: String): Flow<List<Item>>
// Searchqueries HOME-Fragment
fun getItemListHome(state: SearchByState, search: String) : Flow<List<Item>> =
when (state) {
SearchByState.BY_NAME -> getItemListHomeName(search)
SearchByState.BY_TASTE -> getItemListHomeTaste(search)
SearchByState.NO_SEARCH -> getItemListHomeNone()
}
@Query("SELECT nr, name, taste, marke, mag, fav FROM tabak WHERE name LIKE '%' || :search || '%' ORDER BY name ASC")
fun getItemListHomeName(search: String): Flow<List<Item>>
@Query("SELECT nr, name, taste, marke, mag, fav FROM tabak WHERE geschmack LIKE '%' || :search || '%' ORDER BY taste ASC")
fun getItemListHomeTaste(search: String): Flow<List<Item>>
@Query("SELECT nr, name, taste, marke, mag, fav FROM tabak WHERE nr = 0 ORDER BY taste ASC")
fun getItemListHomeNone(): Flow<List<Item>>
/**
* SQL-Marke
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(marke: Marke)
@Update
suspend fun update(marke: Marke)
@Delete
suspend fun delete(marke: Marke)
@Query("SELECT marke FROM marke ORDER BY nr")
suspend fun getMarkeListe(): List<String>
@Query("SELECT nr FROM marke WHERE marke = :marke")
suspend fun getMarkeNr(marke: String): Int
}
So my question. Can you help me to get rid of this error? What did I just do wrong, or what can I do to handle it.
Thank you!
Содержание
- Understanding java.lang.reflect.InvocationTargetException and why it occurs
- Reason for java.lang.reflect.InvocationTargetException
- Handle InvocationTargetException
- Was this post helpful?
- Share this
- report this ad Related Posts
- Author
- Related Posts
- [Fixed] Unsupported class file major version 61 in Java
- [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
- [Fixed] java.util.HashMap$Values cannot be cast to class java.util.List
- [Fixed] Unable to obtain LocalDateTime from TemporalAccessor
- How to Resolve InvocationTargetException in Java
- What Causes InvocationTargetException
- InvocationTargetException Example
- How to Resolve InvocationTargetException
- Track, Analyze and Manage Java Errors With Rollbar
- Что вызывает java.lang.reflect.Исключение InvocationTargetException?
- 1. Обзор
- 2. Причина исключения InvocationTargetException
- 3. Как обрабатывать исключение InvocationTargetException?
- 4. Заключение
- What Causes java.lang.reflect.InvocationTargetException?
- Overview
- What is Java reflection?
- java.lang.reflect.InvocationTargetException
- What causes java.lang.reflect.InvocationTargetException?
- How to handle with java.lang.reflect.InvocationTargetException?
- Conclusion
Understanding java.lang.reflect.InvocationTargetException and why it occurs
In this post, we will see about java.lang.reflect.InvocationTargetException .
You might get java.lang.reflect.InvocationTargetException while working with reflection in java.
Reason for java.lang.reflect.InvocationTargetException
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.
Create anther class to call getLengthOfString using reflection.
Output:
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.
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.
Now when we run ReflectionMain.java again, you will see below output:
That’s all about java.lang.reflect.InvocationTargetException in java.
Was this post helpful?
[Fixed] no suitable driver found for jdbc
Cannot find symbol Java
[Fixed] Unsupported class file major version 61 in Java
Table of ContentsReason for Unsupported class file major version 61 in JavaSolution for Unsupported class file major version 61 in JavaAndorid studio/Intellij Idea with gradleAny other scenario In this post, we will see how to fix Unsupported class file major version 61 in Java. Reason for Unsupported class file major version 61 in Java You […]
[Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
Table of ContentsReason for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListFixes for java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayListUse ArrayList’s constructorAssign Arrays.asList() to List reference rather than ArrayList In this post, we will see how to fix java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList. ClassCastException is runtime exception which indicate that code has tried to […]
[Fixed] java.util.HashMap$Values cannot be cast to class java.util.List
Table of ContentsWhy HashMap values cannot be cast to list?Fix for java.util.HashMap$Values cannot be cast to class java.util.List In this post, we will see how to fix error java.util.HashMap$Values cannot be cast to class java.util.List. Why HashMap values cannot be cast to list? HashMap values returns java.util.Collection and you can not cast Collection to List […]
[Fixed] Unable to obtain LocalDateTime from TemporalAccessor
Table of ContentsUnable to obtain LocalDateTime from TemporalAccessor : ReasonUnable to obtain LocalDateTime from TemporalAccessor : FixLocalDate’s parse() method with atStartOfDay()Use LocalDate instead of LocalDateTime In this article, we will see how to fix Unable to obtain LocalDateTime from TemporalAccessor in Java 8. Unable to obtain LocalDateTime from TemporalAccessor : Reason You will generally get […]
Источник
How to Resolve InvocationTargetException in Java
Table of Contents
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:
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:
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:
Running the above will print out the stack trace of the underlying ArithmeticException :
Track, Analyze and Manage Java Errors With Rollbar
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.
Источник
Что вызывает 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 .
Источник
What Causes java.lang.reflect.InvocationTargetException?
Table of Contents
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.
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
This code snipped is for the invocation of:
And the output is:
The output list down the names of all methods of class java.util.Stack, along with their fully qualified parameter and return types.
java.lang.reflect.InvocationTargetException
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:
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:
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:
Output generated from the getCause() method is shown below, it clearly states the type of underlying exception:
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.
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 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.
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.
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.
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
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.