Project Lombok is a Java library that helps reduce boilerplate code. Java is a very verbose language where repetitive code like getters, setters, and so on can be avoided. Lombok reduces boilerplate code with annotations that get plugged during the build process.
Lombok can 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, then 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>
Consider we have a Person
class with two attributes age
and name
. In order for clients to access the attributes, the Person
class has to provide getters. The following code shows how to write getters in vanilla Java.
public class Main {static class Person{private int age;private String name;public Person(int age, String name) {this.age = age;this.name = name;}public int getAge() {return age;}public String getName() {return name;}}public static void main(String[] args) {Person person = new Person(15, "sam");System.out.println("Person Age - " + person.getAge());System.out.println("Person Name - " + person.getName());}}
@Getter
annotationThe @Getter
annotation is used to generate the default getter implementation for fields that are annotated with the annotation. This annotation can also be used at the class level in which Lombok will generate the getter methods for all fields.
The default implementation is to return the field as it is. For example, if the field is age
, Lombok will generate the getter method, getAge()
. The generated method is public by default unless an AccessLevel
is specified. The list of available access levels is PUBLIC
, PROTECTED
, PACKAGE
, and PRIVATE
.
The following code shows how the annotation reduces the generation of getters to a single annotation.
import lombok.Getter; public class Main { static class Person{ @Getter private int age; @Getter private String name; public Person(int age, String name) { this.age = age; this.name = name; } } @Getter static class NewPerson{ private int age; private String name; public NewPerson(int age, String name) { this.age = age; this.name = name; } } public static void main(String[] args) { Person person = new Person(15, "sam"); System.out.println("Person Age - " + person.getAge()); System.out.println("Person Name - " + person.getName()); System.out.println("------"); NewPerson newPerson = new NewPerson(30, "new-sam"); System.out.println("New Person Age - " + newPerson.getAge()); System.out.println("New Person Name - " + newPerson.getName()); } }