What is the @AllArgsConstructor 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.
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 annotation
The @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;}}
Explanation
In the above code snippet:
- Lines 1 and 2: We import the relevant annotations.
- Lines 6 to 19: We define a
VanillaPersonclass where we declare different kinds of fields. The all argument constructor consists of two fields. There is a null check for thedobfield in the constructor. - Lines 21 to 29: We define a
LombokPersonclass where we simplify theVanillaPersonclass using the@AllArgsConstructorannotation. TheVanillaPersoncan be also considered as the de-lomboked version of theLombokPersonclass.