Warm tip: This article is reproduced from stackoverflow.com, please click
java annotations lombok

Why would I use Lombok-Annotation @NonNull?

发布于 2020-03-29 21:02:01

Lombok offers the annotation @NonNull which executes the nullcheck and throws a NPE (if not configured differently).

I do not understand why I would use that annotation as described in the example of that documentation:

private String name;
public NonNullExample(@NonNull Person person) {
    super("Hello");
    if (person == null) {
      throw new NullPointerException("person is marked @NonNull but is null");
    }
    this.name = person.getName();
  }

The NPE would be thrown anyway. The only reason here to use the annotation imo is if you would want the exception to be different from a NPE.

EDIT: I do know that the Exception would be thrown explicitly and thus 'controlled', but at least the text of the error message should be editable, shouldn't it?

Questioner
metters
Viewed
51
mernst 2019-06-25 00:00

Writing a type annotation such as @NonNull serves several purposes.

  • It is documentation: it communicates the method's contract to clients, in a more concise and precise way than Javadoc text.
  • It enables run-time checking -- that is, it guarantees that your program crashes with a useful error message (rather than doing something worse) if a buggy client mis-uses your method. Lombok does this for you, without forcing the programmer to write the run-time check. The referenced example shows the two ways to do this: with a single @NonNull annotation or with an explicit programmer-written check. The "Vanilla Java" version either has a typo (a stray @NonNull) or shows the code after Lombok processes it.
  • It enables compile-time checking. A tool such as the Checker Framework gives a guarantee that the code will not crash at run time. Tools such as NullAway, Error Prone, and FindBugs are heuristic bug-finders that will warn you about some mis-uses of null but do not give you a guarantee.