Sonaqube Version: * Version 8.9.9 (build 56886)
Rule: Null pointers should not be dereferenced - “getName()” can return null
Codesample:
class Playground {
public static void main(String[ ] args) {
Response response = null;
if(response != null && response.getName() != null && response.getName().equals("")) {
if(response.getName().equals("a")) {
System.out.println("This is also a false-positive I also get an Error for that, but clearly it is checked before");
}
System.out.println("Hello world");
}else {
System.out.println("No NullPointer even it is null");
}
}
}
class Response {
String name;
String result;
public String getName(){return name;}
public String getResult(){return result;}
}
Expected Solution:
The Rule is not triggered when before a NullCheck was made at the IF clause.
But what is about the second - False Positive ? Here the same even in a new if ?
if(response != null && response.getName() != null ) {
if(response.getName().equals("a")) {
System.out.println("This is also a false-positive I also get an Error for that, but clearly it is checked before");
}
}
The situation is the same in this second example: if getName() returns null on the second call, you will have a NPE.
As mentioned in the other post, either you accept the code as it is, or change it to something like: