12

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.

adimoh
  • 658
  • 2
  • 8
  • 20
  • I don't think so. The above question is way too generic and covers many @NonNull annotation. I wish to compare only among two. – adimoh Feb 05 '19 at 15:37
  • You said, "I just to know the better of the two." Which annotation is best depends on your needs, which you have not stated. The discussion at the linked question gives a lot of information to help you make an informed decision. – mernst Feb 06 '19 at 17:43

1 Answers1

12

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.

Community
  • 1
  • 1
akortex
  • 5,067
  • 2
  • 25
  • 57
  • I am new to using these annotations. Which way would you suggest is the best and cleanest way to prevent null references passed to method arguments? @Aris_Kortex – adimoh Feb 05 '19 at 16:02
  • This really depends on what you want to achieve. First and foremost you need to understand that `Lombok` is a third party library and thus adding it to your project may ensue consequences. Also `Lombok` requires specific IDE plugins in order to work. If you're working non solo on a project, adding it may confuse your fellow developers, as `Lombok` does much more than null checks. Without providing more information about your use cases as well as what are you using to build your application, this question is very hard to get answered. – akortex Feb 05 '19 at 16:15