0

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?

RGG
  • 33
  • 1
  • 12

1 Answers1

2

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.

Josef Prochazka
  • 1,273
  • 2
  • 9
  • 28
  • 1
    See also [this](https://stackoverflow.com/questions/37972859/java-util-objects-isnull-vs-object-null) SO question. – Jeroen Heier Jul 02 '18 at 16:08