1

i use very often the check getClass().isInstance() when overriding the equals method of a Java class, as in the following example:

1 - public boolean equals(Object obj){
2 -    if(getClass().isInstance(obj)){
3 -         MyClass cls= (MyClass) obj;
4 -         return obj.getId().equals(this.id);
5 -    }
6 -    return false;
7 - }

Feeding that code to SonarQube (versione 6.7.2) i get the following bug message on line code 4:

A "NullPointerException" could be thrown; "obj" is nullable here.

But according to Javadoc of isInstance() method that's not true:

The method returns true if the specified Object argument is non-null and can be cast to the reference type represented by this Class object without raising a ClassCastException. It returns false otherwise.

So obj on line 4 can't be null. Therefore, my question is: why Sonar detects it as a bug? If it's not a bug as i think, there's a way to tell Sonar to ignore situations like that.

Thank you in advance.

Fabio

0 Answers0