RGG
RGG

Reputation: 33

Sonar gives NullPointerException not right

I am having java code:

public class Test {

  public static void main(String[] args) {
    Student student = new Student(1,"test");
    printId(student);
  }

  private static void printId(Student obj) {
    if(Objects.isNull(obj))
      return;
    System.out.println("Id: " + obj.getId());
  }

}

public class Student {

  private int id;
  private String name;

  public Student(int id, String name) {
    this.id = id;
    this.name = name;
  }

  public int getId(){
    return id;
  }

}

At line System.out.println... sonar is showing that obj can be null but I had already checked for null value.

Is there any way to get rid of this issue?

Upvotes: 0

Views: 1323

Answers (1)

Josef Prochazka
Josef Prochazka

Reputation: 1283

You could use explicit null test.

if(null==obj) 
return;
......

The rule itself does not recognize usage of Objects.isNull as null check. Objects.isNull(Object obj) returns result of null==obj expresion so it can be safely replaced.

However you could contact SonarSource and propose rule change.

Upvotes: 2

Related Questions