What is the @NonNull annotation in Lombok?
What is Lombok?
Project Lombok is a Java library that helps reduce
Lombok can easily be added to the project by adding it as one of the dependencies.
If the project is a Gradle project, we can add the following two lines to the dependencies section of the build.gradle file:
compileOnly 'org.projectlombok:lombok:1.18.22'
annotationProcessor 'org.projectlombok:lombok:1.18.22'
If the project is a Maven project, we can add the following lines to the dependencies section of the pom.xml file:
<dependencies><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.22</version><scope>provided</scope></dependency></dependencies>
@NonNull annotation
The @NonNull annotation generates a null check for fields and arguments annotated with this annotation. This annotation can be used on fields, constructor arguments, and method arguments.
import lombok.NonNull;public class Main {@Setter@Getterstatic class Person{@NonNullprivate int age;private String name;public LombokPerson(@NonNull String firstName, @NonNull String lastName){name = firstName + lastName;}public double calculateTax(@NonNull int salary){return 0.30 * salary;}}static class VanillaPerson{private Integer age;private String name;public VanillaPerson(String firstName, String lastName) {if(firstName == null) throw new NullPointerException("firstName is marked non-null but is null");if(lastName == null) throw new NullPointerException("lastName is marked non-null but is null");name = firstName + lastName;}public int getAge() {return age;}public void setAge(Integer age) {if(age == null) throw new NullPointerException("age is marked non-null but is null");this.age = age;}public double calculateTax(Integer salary){if(salary == null) throw new NullPointerException("salary is marked non-null but is null");return 0.30 * salary;}}}
Explanation
- Line 1: We import the annotation.
- Line 5: We define a
Personclass and annotate it with the@Getterand@Setterannotation. - Line 9–10: We annotate the field
agewith@NonNulland indicate that this field should not benull. Upon delomboking the code, thenullcheck for theagefield will be in the setter method of the field. - Line 14: The constructor arguments
firstName,lastNameare annotated with@NonNull. On delomboking the code, thenullcheck for the constructor arguments will be inserted immediately following any explicitthis()orsuper()calls in the constructor. - Line 18: The method argument
salaryis annotated with@NonNull. On delomboking the code, thenullcheck for the method arguments will be inserted first in the method.
The delomboked code is similar to the VanillaPerson class.
Note: Delomboking is the process of converting Lombok annotations to vanilla Java code.