javasonarqubesonarlint-intellij

SonarLint on Optional.ofNullable: A "NullPointerException" could be thrown


I am getting sonar warning A "NullPointerException" could be thrown; "test" is nullable here. inside the if condition:

public record Test(String x) {
  public static void main(String[] args) {
    Test test = new Test("x");
    printXLength(test);
  }

  private static void printXLength(Test test) {
    if (Optional.ofNullable(test).map(test1 -> test1.x).isPresent()) {
      System.out.println(test.x.length());
    }
  }
}

I set the test variable to null and ran it, it didn't throw NPE.

Is it false positive ? Or am I missing something?


Solution

  • On this line:

    if (Optional.ofNullable(test).map(test1 -> test1.x).isPresent())
    

    the call to isPresent() doesn't directly check if test is present; it checks if the result of the map call is present - hence it only checks the presence of test indirectly. Sonarlint is not clever enough to go through all the data flow involved to determine that test itself can't be null here.

    Try changing it to the following:

      private static void printXLength(Test test) {
        Optional.ofNullable(test).map(test1 -> test1.x).ifPresent(
          x -> System.out.println(x.length())
        )
      }