Why does IntelliJ tell me that the link cannot be null in this situation?

This is the code I have:

private void foo(Bar bar) { Session session = null; Class entityClazz = null; try { entityClazz = Hibernate.getClass(bar); if (bar != null) { 

And IntelliJ will warn me of the last statement above with the message:

The condition "bar! = Null" is always "true". This inspection analyzes the method control and data flow to report possible conditions that are always true or false, expressions whose value has been statically constant, and situations that can lead to the nullification of contract violations.

When I delete the instruction:

 entityClazz = Hibernate.getClass(bar); 

there will be no warning.

What happens in IntelliJ, does the stop from the bar stop here?

+5
source share
1 answer

According to the sleep mode documentation, this is the getClass () method in the org.hibernate.Hibernate class.

 public static Class getClass(Object proxy) { if ( proxy instanceof HibernateProxy ) { return ( ( HibernateProxy ) proxy ).getHibernateLazyInitializer() .getImplementation() .getClass(); } else { return proxy.getClass(); } } 

According to the documentation, a HibernateException is NestableRuntimeException in case of a null parameter, which is an extended class of NestableRuntimeException also a RuntimeException .

Intellij is able to analyze this using its code checks, it is easy to find that loc

 entityClazz = Hibernate.getClass(bar); 

will throw NPE. If it throws an NPE, the if condition is never reached, since the NestableRuntimeException is an exception.

You can put an if condition above Hibernate.getClass (bar), which would be ideal for a null safe method.

Hope this clears up.

References

Hibernate documentation

Code Analysis - Intellij

Code Verification - Intellij

+3
source

Source: https://habr.com/ru/post/1247010/


All Articles