Scan does not know that java.lang.Class.isInstance(o) returns false if o == null

java

(Niels Basjes) #1

I’m using SonarLint IntelliJ 3.5.1.2759 and the Sonar maven plugin version 3.5.0.1254 and both report the following incorrect error.

Assume the simple Example class with a single property private String foo;
And this equals method:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (Example.class.isInstance(o)) return false;
    Example example = (Example) o;
    return Objects.equals(foo, example.foo);
}

Then Sonar reports that the example variable can be null and thus the dereference on the last line may cause an NPE.

The message in SonarLint is

A "NullPointerException" could be thrown; "example" nullable here. 

This is incorrect because the java.lang.Class.isInstance(o) always returns false if the provided parameter is null.

Snippet from the JavaDoc of this method:

The method returns true if the specified Object argument is non-null and ...
It returns false otherwise.