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
annotationThe @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;}}}
Person
class and annotate it with the @Getter
and @Setter
annotation.age
with @NonNull
and indicate that this field should not be null
. Upon delomboking the code, the null
check for the age
field will be in the setter method of the field.firstName
, lastName
are annotated with @NonNull
. On delomboking the code, the null
check for the constructor arguments will be inserted immediately following any explicit this()
or super()
calls in the constructor.salary
is annotated with @NonNull
. On delomboking the code, the null
check 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.