Which @NotNull Java annotation should I use?

I’m looking to make my code more readable as well as use tooling like IDE code inspection and/or static code analysis (FindBugs and Sonar) to avoid NullPointerExceptions. Many of the tools seem incompatible with each others’ @NotNull/@NonNull/@Nonnull annotation and listing all of them in my code would be terrible to read. Any suggestions of which one is the ‘best’? Here is the list of equivalent annotations I’ve found:

  • javax.validation.constraints.NotNull
    Created for runtime validation, not static analysis.
    documentation

  • edu.umd.cs.findbugs.annotations.NonNull
    Used by FindBugs (dead project) and its successor SpotBugs static analysis and therefore Sonar (now Sonarqube)
    FindBugs documentation, SpotBugs documentation

  • javax.annotation.Nonnull
    This might work with FindBugs too, but JSR-305 is inactive. (See also: What is the status of JSR 305?)
    source

  • org.jetbrains.annotations.NotNull
    Used by IntelliJ IDEA IDE for static analysis.
    documentation

  • lombok.NonNull
    Used to control code generation in Project Lombok.
    Placeholder annotation since there is no standard.
    source,
    documentation

  • androidx.annotation.NonNull
    Marker annotation available in Android, provided by annotation package
    documentation

  • org.eclipse.jdt.annotation.NonNull
    Used by Eclipse for static code analysis
    documentation

2
25

Leave a Comment