7

I am using the lombok @NonNull annotation for some of my fields, parameters and methods, partly for null checking, and also partly for documentation purpose. It is then confusing if I added a @NonNull/@NotNull annotation from other libraries.

Then if I also want to add a @Nullable/@CanNull annotation for some of my code, which one should I use? It doesn't exist in lombok (reasonably). If I declare my own annotation, IDEs may not understand them. If I use these annotations from existing libraries, other @NotNull annotations will also get added, and they may easily lead to using wrong annotations when I want the lombok one.

1 Answer 1

3

Per the lombok documentation:

Lombok has always treated various annotations generally named @NonNull on a field as a signal to generate a null-check if lombok generates an entire method or constructor for you, via for example @Data. However, using lombok's own @lombok.NonNull on a parameter or record component results in the insertion of the null-check at the top of that method.

Therefore, if you don't want lombok to insert a run-time null check, there is no reason to use lombok's @NonNull annotation. You can use an annotation, from any package, named @NonNull, with the same documentation benefits. Furthermore, most Java tools have the same policy: no matter which @NonNull you use, they will read and respect the annotation, just as if you had used their own proprietary one.

If you really want lombok to insert null checks, then you have no choice other than to use @NonNull and @Nullable from different packages.

This question is also relevant: What @Nullable to use in Java (as of 2023/JDK21)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.