Java lang reflect invocationtargetexception null как исправить

Java code occasionally reports an error, but it will not report an error under normal circumstances.

Error background

Java code occasionally reports an error, but it will not report an error under normal circumstances.

exception: java.lang.reflect.InvocationTargetException: null

2020-05-11 at 15:17:39 CST traceId:[] ERROR io.netty.util.internal.logging.AbstractInternalLogger 91 error-Unexpected exception: java.lang.reflect.InvocationTargetException: null 
    at sun.reflect.GeneratedMethodAccessor214. invoke(Unknown Source) ~[?:? ]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java: 43) ~[?:1.8 .0_192]
    at java.lang.reflect.Method.invoke(Method.java: 498) ~[?:1.8 .0_192]
    at org.yeauty.pojo.PojoEndpointServer.doOnClose(PojoEndpointServer.java: 121) [netty-websocket-spring-boot-starter-0.8.0.jar!/:? ]
    at org.yeauty.standard.WebSocketServerHandler.channelInactive(WebSocketServerHandler.java: 29) [netty-websocket-spring-boot-starter-0.8.0.jar!/:? ]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java: 257) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java: 243) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java: 236) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.handler.codec.ByteToMessageDecoder.channelInputClosed(ByteToMessageDecoder.java: 393) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.handler.codec.ByteToMessageDecoder.channelInactive(ByteToMessageDecoder.java: 358) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java: 257) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java: 243) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java: 236) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive(DefaultChannelPipeline.java: 1416) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java: 257) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java: 243) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java: 912) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.channel.AbstractChannel$AbstractUnsafe$ 8.run(AbstractChannel.java:816) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java: 163) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java: 416) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java: 515) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor$ 5.run(SingleThreadEventExecutor.java:918) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.util.internal.ThreadExecutorMap$ 2.run(ThreadExecutorMap.java:74) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java: 30) [netty-all-4.1.38.Final.jar!/:4.1.38 .Final]
    at java.lang.Thread.run(Thread.java: 748) [?:1.8 .0_192]
Caused by: java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextNode(HashMap.java: 1445) ~[?:1.8 .0_192]
    at java.util.HashMap$EntryIterator.next(HashMap.java: 1479) ~[?:1.8 .0_192]
    at java.util.HashMap$EntryIterator.next(HashMap.java: 1477) ~[?:1.8 .0_192]
    at com.jcdz.hbdservice.websocket.ServerWebSocket1.onClose(ServerWebSocket1.java: 38) ~[coalminehbdservice-1.0.jar!/:1.0 ]
    ... 25 more

Reason for error

There are many reasons for the error, I will only say the reason I came into contact:

(1) If (==) judgment statement is wrong

if( devMap. getOrDefault ( “locationcode”,”” ) == null )

devMap.get( “locationcode” ) : It is possible that a null is passed, and a null pointer will appear at this time

View the source code of getOrDefault()

1  /** 
2       * Returns the value to which the specified key is mapped, or
 3       * { @code defaultValue} if this map contains no mapping for the key.
 4       *
 5       * @implSpec
 6       * The default implementation makes no guarantees about synchronization
 7       * or atomicity properties of this method. Any implementation providing
 8       * atomicity guarantees must override this method and document its
 9       * concurrency properties.
 10       *
 11       * @param key the key whose associated value is to be returned
12       * @param defaultValue the default mapping of the key
 13       * @return the value to which the specified key is mapped, or
 14       * { @code defaultValue} if this map contains no mapping for the key
 15       * @throws ClassCastException if the key AN of inappropriate type for IS
 16       * the this Map
 . 17       * (<a href="{@%20docroot%20}/java/util/Collection.html#optional-restrictions"> optional </a>)
 18 is       * @throws a NullPointerException IF The specified key is null and this map
 19      * does not permit null keys
 20       * (<a href="{@%20docRoot%20}/java/util/Collection.html#optional-restrictions">optional</a>)
 21       * @since 1.8
 22       */ 
23      default V getOrDefault (Object key, V defaultValue) {
 24          V v;
 25          return (((v = get(key)) != null ) || containsKey(key))
 26              ? V
 27              : defaultValue;
 28      }

@throws NullPointerException if the specified key is null and this map does not allow null keys

We can see that there is a get(key) method in the getOrDefault () method. At this time, if the value of key is a null, an error will be reported, such as key:null.

When the value of map is passed in, it is necessary to avoid the phenomenon of passing in map.put(key: null). You can use map.put(key: “”) instead.

(2) if (equals) judgment statement is wrong

if(! time .equals( “1900-01-01 00:00:00” ))

time : it is possible to pass a null, then there will be a null pointer phenomenon

Error resolution

Modify the sequence of judgment statements as follows:

if( null == devMap getOrDefault ( “locationcode”,”” ))

if(! “1900-01-01 00:00:00”.equals(time))

Read More:

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

Содержание

  1. Understanding java.lang.reflect.InvocationTargetException and why it occurs
  2. Reason for java.lang.reflect.InvocationTargetException
  3. Handle InvocationTargetException
  4. Was this post helpful?
  5. Share this
  6. report this ad Related Posts
  7. Author
  8. Related Posts
  9. [Fixed] Unsupported class file major version 61 in Java
  10. [Fixed] java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
  11. [Fixed] java.util.HashMap$Values cannot be cast to class java.util.List
  12. [Fixed] Unable to obtain LocalDateTime from TemporalAccessor
  13. Troubleshooting
  14. NoSuchMethodException Due to Type Erasure
  15. IllegalAccessException when Invoking a Method
  16. IllegalArgumentException from Method.invoke()
  17. InvocationTargetException when Invoked Method Fails
  18. How to Resolve InvocationTargetException in Java
  19. What Causes InvocationTargetException
  20. InvocationTargetException Example
  21. How to Resolve InvocationTargetException
  22. Track, Analyze and Manage Java Errors With Rollbar
  23. What Causes java.lang.reflect.InvocationTargetException?
  24. Overview
  25. What is Java reflection?
  26. java.lang.reflect.InvocationTargetException
  27. What causes java.lang.reflect.InvocationTargetException?
  28. How to handle with java.lang.reflect.InvocationTargetException?
  29. 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 […]

Источник

Troubleshooting

This section contains examples of problems developers might encounter when using reflection to locate, invoke, or get information about methods.

NoSuchMethodException Due to Type Erasure

The MethodTrouble example illustrates what happens when type erasure is not taken into consideration by code which searches for a particular method in a class.

When a method is declared with a generic parameter type, the compiler will replace the generic type with its upper bound, in this case, the upper bound of T is Object . Thus, when the code searches for lookup(Integer) , no method is found, despite the fact that the instance of MethodTrouble was created as follows:

Searching for lookup(Object) succeeds as expected.

In this case, find() has no generic parameters, so the parameter types searched for by getMethod() must match exactly.

IllegalAccessException when Invoking a Method

An IllegalAccessException is thrown if an attempt is made to invoke a private or otherwise inaccessible method.

The MethodTroubleAgain example shows a typical stack trace which results from trying to invoke a private method in an another class.

The stack trace for the exception thrown follows.

IllegalArgumentException from Method.invoke()

Method.invoke() has been retrofitted to be a variable-arity method. This is an enormous convenience, however it can lead to unexpected behavior. The MethodTroubleToo example shows various ways in which Method.invoke() can produce confusing results.

Since all of the parameters of Method.invoke() are optional except for the first, they can be omitted when the method to be invoked has no parameters.

The code in this case generates this compiler warning because null is ambiguous.

It is not possible to determine whether null represents an empty array of arguments or a first argument of null .

This fails despite the fact that the argument is null , because the type is a Object and ping() expects no arguments at all.

This works because new Object[0] creates an empty array, and to a varargs method, this is equivalent to not passing any of the optional arguments.

Unlike the previous example, if the empty array is stored in an Object , then it is treated as an Object . This fails for the same reason that case 2 fails, ping() does not expect an argument.

InvocationTargetException when Invoked Method Fails

An InvocationTargetException wraps all exceptions (checked and unchecked) produced when a method object is invoked. The MethodTroubleReturns example shows how to retrieve the original exception thrown by the invoked method.

Источник

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.

Источник

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.

Источник

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.

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.

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

Kuangcp opened this issue

Apr 24, 2018

· 10 comments

Comments

@Kuangcp

04-24 14:24:23.133 | restartedMain |-INFO t.k.graduate.GraduateApplication:50 — Starting GraduateApplication on youai with PID 18093 (/home/kcp/IdeaProjects/Base/graduate/out/production/classes started by kcp in /home/kcp/IdeaProjects/Base)
04-24 14:24:23.134 | restartedMain |-INFO t.k.graduate.GraduateApplication:663 — The following profiles are active: dev
04-24 14:24:23.213 | restartedMain |-INFO o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext:590 — Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@5ffe2d6: startup date [Tue Apr 24 14:24:23 CST 2018]; root of context hierarchy
04-24 14:24:23.831 | restartedMain |-INFO o.s.d.r.c.RepositoryConfigurationDelegate:163 — Multiple Spring Data modules found, entering strict repository configuration mode!
04-24 14:24:23.878 | restartedMain |-INFO o.s.d.r.c.RepositoryConfigurationDelegate:163 — Multiple Spring Data modules found, entering strict repository configuration mode!
04-24 14:24:23.887 | restartedMain |-INFO o.s.d.r.c.RepositoryConfigurationExtensionSupport:297 — Spring Data Redis — Could not safely identify store assignment for repository candidate interface top.kuangcp.graduate.dao.StudentDao.
04-24 14:24:24.205 | restartedMain |-INFO o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker:328 — Bean ‘org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration’ of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$57a3be0e] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
04-24 14:24:24.453 | restartedMain |-INFO o.s.b.w.e.tomcat.TomcatWebServer:91 — Tomcat initialized with port(s): 8889 (http)
04-24 14:24:24.462 | restartedMain |-INFO o.a.coyote.http11.Http11NioProtocol:180 — Initializing ProtocolHandler [«http-nio-8889»]
04-24 14:24:24.467 | restartedMain |-INFO o.a.catalina.core.StandardService:180 — Starting service [Tomcat]
04-24 14:24:24.467 | restartedMain |-INFO o.a.catalina.core.StandardEngine:180 — Starting Servlet Engine: Apache Tomcat/8.5.29
04-24 14:24:24.470 | localhost-startStop-1 |-INFO o.a.c.core.AprLifecycleListener:180 — The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib]
04-24 14:24:24.523 | localhost-startStop-1 |-INFO o.a.c.c.C.[Tomcat].[localhost].[/]:180 — Initializing Spring embedded WebApplicationContext
04-24 14:24:24.523 | localhost-startStop-1 |-INFO o.s.web.context.ContextLoader:285 — Root WebApplicationContext: initialization completed in 1310 ms
04-24 14:24:24.608 | localhost-startStop-1 |-INFO o.s.b.w.s.FilterRegistrationBean:244 — Mapping filter: ‘characterEncodingFilter’ to: [/]
04-24 14:24:24.608 | localhost-startStop-1 |-INFO o.s.b.w.s.DelegatingFilterProxyRegistrationBean:244 — Mapping filter: ‘springSecurityFilterChain’ to: [/
]
04-24 14:24:24.608 | localhost-startStop-1 |-INFO o.s.b.w.s.ServletRegistrationBean:185 — Servlet dispatcherServlet mapped to [/]
04-24 14:24:24.800 | restartedMain |-INFO com.zaxxer.hikari.HikariDataSource:110 — HikariPool-1 — Starting…
04-24 14:24:24.835 | restartedMain |-INFO com.zaxxer.hikari.pool.PoolBase:516 — HikariPool-1 — Driver does not support get/set network timeout for connections. (这个 org.postgresql.jdbc.PgConnection.getNetworkTimeout() 方法尚未被实作。)
04-24 14:24:24.845 | restartedMain |-INFO com.zaxxer.hikari.HikariDataSource:123 — HikariPool-1 — Start completed.
04-24 14:24:24.881 | restartedMain |-INFO o.s.o.j.LocalContainerEntityManagerFactoryBean:361 — Building JPA container EntityManagerFactory for persistence unit ‘default’
04-24 14:24:24.930 | restartedMain |-INFO org.hibernate.Version:45 — HHH000412: Hibernate Core {5.2.16.Final}
04-24 14:24:24.931 | restartedMain |-INFO org.hibernate.cfg.Environment:213 — HHH000206: hibernate.properties not found
04-24 14:24:24.957 | restartedMain |-INFO o.h.annotations.common.Version:66 — HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
04-24 14:24:25.035 | restartedMain |-INFO org.hibernate.dialect.Dialect:157 — HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL95Dialect
04-24 14:24:25.098 | restartedMain |-INFO o.h.e.j.e.i.LobCreatorBuilderImpl:124 — HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException
java.lang.reflect.InvocationTargetException: null
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.useContextualLobCreation(LobCreatorBuilderImpl.java:113)
at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.makeLobCreatorBuilder(LobCreatorBuilderImpl.java:54)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.(JdbcEnvironmentImpl.java:271)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:861)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:888)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1761)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1698)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:579)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:859)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243)
at top.kuangcp.graduate.GraduateApplication.main(GraduateApplication.java:13)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.sql.SQLFeatureNotSupportedException: 这个 org.postgresql.jdbc.PgConnection.createClob() 方法尚未被实作。
at org.postgresql.Driver.notImplemented(Driver.java:640)
at org.postgresql.jdbc.PgConnection.createClob(PgConnection.java:1297)
… 49 common frames omitted
04-24 14:24:25.100 | restartedMain |-INFO org.hibernate.type.BasicTypeRegistry:148 — HHH000270: Type registration [java.util.UUID] overrides previous : org.hibernate.type.UUIDBinaryType@3c5e620a
04-24 14:24:25.393 | restartedMain |-INFO o.s.o.j.LocalContainerEntityManagerFactoryBean:415 — Initialized JPA EntityManagerFactory for persistence unit ‘default’

@Kuangcp

Gradle runtime(‘org.postgresql:postgresql:42.2.2’)

Docker Image

postgres 9.6-alpine b27674feae2a 7 weeks ago 38 MB

@davecramer

@Kuangcp

@vlsi

@davecramer , @Kuangcp , one of the ways to «fix» this is to actually implement PgConnection.createClob :)

@davecramer

true enough… is there an issue for it ?

@devpreview

I have the same error:

java.lang.reflect.InvocationTargetException: null
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
	at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
	at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.useContextualLobCreation(LobCreatorBuilderImpl.java:113) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.makeLobCreatorBuilder(LobCreatorBuilderImpl.java:54) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:271) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:861) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:888) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
	at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1761) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1698) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:579) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:859) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]

As hotfix this issue set

hibernate.temp.use_jdbc_metadata_defaults=false
hibernate.dialect=org.hibernate.dialect.PostgreSQL9Dialect.

See also #1102

@davecramer

We’d be more than happy to have someone implement this method

Dave Cramer

On 30 April 2018 at 19:37, Alexey Savchuk ***@***.***> wrote:
I have the same error:

java.lang.reflect.InvocationTargetException: null
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.useContextualLobCreation(LobCreatorBuilderImpl.java:113) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl.makeLobCreatorBuilder(LobCreatorBuilderImpl.java:54) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:271) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:259) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:233) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:242) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:210) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:861) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:888) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1761) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1698) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:579) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:859) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at com.likehostel.application.server.ApplicationServerListener.startCore(ApplicationServerListener.java:52) ~[classes/:na]
at com.likehostel.application.server.ApplicationServerListener.applicationReady(ApplicationServerListener.java:38) ~[classes/:na]
at com.likehostel.application.server.ApplicationServerListener.onApplicationEvent(ApplicationServerListener.java:28) ~[classes/:na]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:400) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:354) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.boot.context.event.EventPublishingRunListener.running(EventPublishingRunListener.java:103) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplicationRunListeners.running(SpringApplicationRunListeners.java:78) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:343) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at com.likehostel.application.server.ApplicationServer.main(ApplicationServer.java:21)


You are receiving this because you modified the open/close state.
Reply to this email directly, view it on GitHub
<#1176 (comment)>, or mute
the thread
<https://github.com/notifications/unsubscribe-auth/AAYz9tKye5wY2UldvOSN6iZFA6OgeWkxks5tt6BUgaJpZM4ThGMM>
.

@jair-anderson-souza

@davecramer

Spring should be following the JDBC spec which specifies that if you don’t implement a method you throw the exception… kick it back to them.

@davecramer

will not fix this is not our bug

Понравилась статья? Поделить с друзьями:
  • Java lang outofmemoryerror no error message
  • Java lang outofmemoryerror java heap space как исправить майнкрафт
  • Java lang outofmemoryerror gc overhead limit exceeded как исправить
  • Java lang out of memory error java heap space
  • Java lang nullpointerexception ошибка как исправить на телефоне