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.
For a Gradle project, 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'
For a Maven project, 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>
@AllArgsConstructor
annotationThe @AllArgsConstructor
annotation generates a constructor with one parameter for every field in the class.
Fields that are annotated with @NonNull
result in null checks with the corresponding parameters in the constructor. The annotation won’t generate a parameter for the static
and initialized final fields.
import lombok.AllArgsConstructor;import lombok.NonNull;public class Main {static class VanillaPerson {private int age;private static String staticAttr;private final String name = "educative";private final String dob;public VanillaPerson(int age, String dob) {if (dob == null) {throw new NullPointerException("dob is marked non-null but is null");}this.age = age;this.dob = dob;}}@AllArgsConstructorstatic class LombokPerson {private int age;private static String staticAttr;private final String name = "educative";@NonNullprivate final long dob;}}
In the above code snippet:
VanillaPerson
class where we declare different kinds of fields. The all argument constructor consists of two fields. There is a null check for the dob
field in the constructor.LombokPerson
class where we simplify the VanillaPerson
class using the @AllArgsConstructor
annotation. The VanillaPerson
can be also considered as the de-lomboked version of the LombokPerson
class.