A "NullPointerException" could be thrown; "ofNullable()" can return null

This is a bug report.

Versions

  • SonarQube Server: v24.12.0.100206
  • Scanner: 4.0.0.4121

How is SonarQube deployed

zip

Checked code

import java.util.Optional;
import org.jspecify.annotations.Nullable;

public record Foo(@Nullable String attribute) {

  @Nullable
  public String bar() {
    return Optional.ofNullable(attribute).filter("bar"::equals).orElse(null);
  }
}

Observed behaviour

Sonar raises a java:S2259 violation. The given explanation is A "NullPointerException" could be thrown; "ofNullable()" can return null.

Expected behaviour

Sonar should not raises a java:S2259 violation because Optional#ofNullable can’t return null.

The same applies to java.util.Objects.requireNonNullElse

Seems like the issue happens with any strong nullable notation (sonar-java/java-frontend/src/main/java/org/sonar/java/model/JSymbolMetadataNullabilityHelper.java at 322b122ea3f0c210ae2d7bbb1434e3005ac3b594 · SonarSource/sonar-java · GitHub) having @Target TYPE_USE:

  • org.jspecify.annotations.Nullable
  • org.eclipse.jdt.annotation.Nullable

FTR, I created A “NullPointerException” could be thrown; “ofNullable()” can return null by reda-alaoui · Pull Request #5046 · SonarSource/sonar-java · GitHub which contains a test case + a fix breaking a less important rule.

Thanks for the bug report and the PR with the minimal example. The underlying issue seems to the same as reported here: FP java:S2259 Optional.map(). We are aware of the issue and took note of your example. Thanks again for sharing.

Cheers,

Romain

1 Like