简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM