In a Java program using JSpecify notations, SonarQube Cloud warns that a method marked @NonNull
may return null, when it may not:
package com.example;
import org.jspecify.annotations.NonNull;
import org.jspecify.annotations.Nullable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
public class SonarExample {
@NonNull
public List<String> getStrings() {
// Sonar says: "This method's return value is marked "@NullMarked at class level" but null is returned."
return Stream.of("one", "two", "three")
.map(SonarExample::toUppercase)
.filter(Objects::nonNull)
.toList();
}
@Nullable
private static String toUppercase(final String string) {
if (string.equals("two")) {
return null;
}
return string.toUpperCase();
}
}
Same happens when using @NullMarked
on the class instead of @NonNull
on the getStrings
method.
If @Nullable
is removed on toUppercase
, the warning goes away.