Lombok's @NonNull or javax @Nonnull

adimoh picture adimoh · Feb 5, 2019 · Viewed 10.4k times · Source

Lombok's @NonNull VS javax.annotation.Nonnull

Which one is better to use for method parameters and when?

The answer here vaguely compares all annotations but has no inference on which one is best. I just to know the better of the two.

Answer

akortex picture akortex · Feb 5, 2019

A simple Google search to find the docs yields the very obvious difference between the two.

javax.annotation.Nonnull is part of JSR-305 which seems to be dead. Even if that wasn't the case said annotation would have only be used for static code analysis purposes, e.g. your IDE warning you that you're passing in a null value someplace where this is not acceptable.

lombok.NonNull is a very different story. First of all, said annotation is NOT used for validation purposes or rather static code analysis purposes. Lombok uses this annotation to fire NPEs whenever an instance variable or a parameter are null when they're not supposed to.

Lombok, being an annotation post processor will effectively pick up this annotation during the pre-compilation process and will auto generate the needed code to effectively handle these cases (by manipulating the AST).

You can read more on this here: Lombok - NonNull.

It seems that your familiarity with both the javax.annotation related functionality and Lombok's functionality is not the best, so I would suggest to have a good read on what is what.