Why is @jakarta.validation.constraints.NotNull use as non null annotation?

Hello,

We are using Jakarta Bean Validation in our project code base and code annotated with @jakarta.validation.constraints.NotNull triggers java:S2589 Expression always evaluate to true in Eclipse.

Versions used:

  • Server : Community Build v25.11.0.114957 Standard Experience
  • Eclipse Plugin : SonarLint for Eclipse 12.6.0.84813 org.sonarlint.eclipse.feature.feature.group SonarSource

As far as I understand from those two links from 2019:

It has already been reported as false positive or fixed.

Yet, I have still the issue : is there something I need to do on my part ? (I do think I am connected with Sonar Server).

Our code:

class Foobar {
  private String x;
  @jakarta.validation.constraints.NotNull 
  public String getX() {return x;}
}

private void myMethod(Foobar source) {
  var x = source.getX(); // annotated with @NotNull
  if (x != null) { // report java:S2589 "Expression always evaluate to true"
    // do something with x
  }
}

Pretty much like the link above, x can be null if (1) validation was not run (2) validation failed (in this case I am performing additional validation that I don’t want to perform using jakarta.validation.ConstraintValidator).

Hello @d721c822,

Thanks for your report! The fix you’re referring was done for another rule, java:S2637. This problem was also investigated in another ticket, and the resolution was the following:

However we cannot simply stop considering @NotNull annotations or we will start raising false positives in rule RSPEC-2259 (“Null pointers should not be dereferenced”). As we are not able to detect if a validation was done before, it is reasonable to suppose that the user can dereference such values without checking if they are null.

So I’m not sure that it’ll be fixed in the near future. Anyway, I’ll reassign this ticket to investigate.

How can I make sure Sonar exclude Jakarta Validation annotation from null checks ?

Currently we don’t provide a way to exclude any specific annotation for this rule. For now you can mark this issue as Won’t Fix / False Positive. Meanwhile we’ll think about probable alternatives. Hope it answers your question.

Hello,

We have applied a change to exclude the runtime validation annotations from the nullability rules. This will be available in the next release.

thank you for your feedback, we appreciate it.