jaxzin jaxzin - 2 months ago 26x
Java Question

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'

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.


  • edu.umd.cs.findbugs.annotations.NonNull

    Used by Findbugs static analysis and therefore Sonar


  • javax.annotation.Nonnull

    This might work with Findbugs too, but JSR-305 is inactive.


  • org.jetbrains.annotations.NotNull

    Used by IntelliJ IDEA IDE for static analysis.


  • lombok.NonNull

    Used to control code generation in Project Lombok.

    Placeholder annotation since there is no standard.


  • android.support.annotation.NonNull

    Marker annotation available in Android, provided by support-annotations package


  • org.eclipse.jdt.annotation.NonNull

    Used by Eclipse for static code analysis



I would only use things under the javax namespace (even though I love what Lombok and IntelliJ are doing). Otherwise, you might be creating a dependency on something other than what the run-time gives you for something that is pretty much semantics. Maybe for some projects, that's ok, but that'd be a deal-breaker for me.

I would use javax.validation.constraints.NotNull because that's already here with Java EE 6.

The javax.annotation.NonNull might not be here until Java 8 (as Stephen pointed out). And the others are not standard annotations.

It would have been nice if annotations were extensible. That way you could define your own non-null annotation inheriting/extending from anything. Then when standards get ironed out, all you would have to do would be to redefine your own custom annotation.

Unfortunately that's not the case.