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

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.
1 Like

Hi @nielsbasjes ,

I believe there is a typo in your example and there should be a negation in the second if. Still I can reproduce your FP even with negation.
Could you explain why using here isInstance and not instanceof ? With instanceof it seems more explicit and FP disappear.

This is the way IntelliJ generates the default implementation.

hello @nielsbasjes,

indeed this looks like false positive, because engine is not aware about behavior of isInstance method (it would work with instanceof operator). I created ticket to handle it https://jira.sonarsource.com/browse/SONARJAVA-3187