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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With