What is the @AllArgsConstructor annotation in Lombok?

What is Lombok?

Project Lombok is a Java library that helps reduce boilerplate codeA section of code repeated in multiple places with a little variation. Java is a very verbose language where repetitive code like getters, setters, etc. can be avoided. Lombok reduces the boilerplate code with its annotations that get plugged during the build process.

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;
}
}
@AllArgsConstructor
static class LombokPerson {
private int age;
private static String staticAttr;
private final String name = "educative";
@NonNull
private 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 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.
  • Lines 21 to 29: We define a 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.