Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is IntelliJ telling me that reference can not 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 for the last statement above with the message:

Condition 'bar != null' is always 'true'. This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.

When I delete the statement:

entityClazz = Hibernate.getClass(bar);

the warning will be gone.

What is going on in IntelliJ 's mind here, what is stopping from bar being null?

like image 448
Koray Tugay Avatar asked Apr 13 '16 07:04

Koray Tugay


1 Answers

As per the hibernate documentation, this is what getClass() method in org.hibernate.Hibernate class does.

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

As per the documentation HibernateException is thrown 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 inspections it is easily found that the loc

entityClazz = Hibernate.getClass(bar);

would throw an NPE. If it throws an NPE, the if condition statement is never reached, as NestableRuntimeException are unchecked exceptions.

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

Hope this clears.

References

Hibernate Documentation

Code Analysis - Intellij

Code Inspection - Intellij

like image 132
aksappy Avatar answered Nov 03 '22 21:11

aksappy