Which @NonNull Java annotation to use [duplicate]

There is no standard @NonNull annotation. Creating such an annotation was the goal of JSR 305, which has been abandoned for a long time. There will not be a standard @NonNull annotation until JSR 305 is reconstituted. Oracle has no current plans to do so. (JEE annotations are outside the scope of JSR 305.)

For futureproofing, the most important factor to consider is whether the annotation is a type annotation or a declaration annotation. Because @NonNull states a property of the variable’s value rather than of the variable itself, it should be a type annotation. Being a type annotation also lets the annotation be written on more locations, as in List<@NonNull String>.

You can determine whether an annotation is a type annotation by looking at the @Target meta-annotation on the annotation’s definition. As of this writing, it seems that only the Checker Framework and Eclipse versions are type annotations, so I would choose them over the ones that are declaration annotations. Note that the developers of any of the other annotations could update them to be type annotations as well; I don’t know of their plans.

The only downside is that using a type annotation requires use of a Java 8 compiler. The Checker Framework has mechanisms for letting code containing its annotations be compiled by a Java 7 compiler.

Leave a Comment