Table of contents
1.
Introduction
2.
Why Project Lombok?
3.
Features of Lombok Project
3.1.
1. `@Getter` and `@Setter`
3.2.
2. `@NoArgsConstructor` and `@AllArgsConstructor`
3.3.
3. `@ToString`
3.4.
4. `@Builder`
3.5.
5. `@Data`
4.
Java Lombok Package
4.1.
1. Maven Dependency
4.2.
2. Gradle Dependency
4.3.
3. Manual Installation
5.
Purpose to Use Lombok Project
6.
Concise Data Object
6.1.
Without Lombok
6.2.
With Lombok
7.
Generating Getters and Setters
7.1.
Without Lombok
7.2.
With Lombok
8.
Configure Lombok in Eclipse IDE
8.1.
1. Download Lombok
9.
2. Run the Lombok Installer
9.1.
3. Restart Eclipse
9.2.
4. Enable Annotation Processing
9.3.
5. Add Lombok to the Project:
9.4.
6. Use Lombok Annotations
10.
Java Program without Using Lombok
10.1.
Java
11.
Java Program with Lombok
11.1.
Java
12.
Frequently Asked Questions
12.1.
Does Lombok work with all Java versions?
12.2.
Can Lombok be used with other libraries & frameworks?
12.3.
Are there any performance impacts when using Lombok?
13.
Conclusion
Last Updated: Aug 8, 2024
Easy

Lombok in Java

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Lombok is a Java library that helps developers write cleaner & more concise code. It does this by generating common code like getters, setters, equals, hashCode & toString methods at compile time using simple annotations. Lombok makes Java classes shorter & easier to read by reducing boilerplate code. 

Lombok in Java

In this article, we'll learn what Lombok is, why it's useful, its key features, how to use it in a Java project & with code examples.

Why Project Lombok?

We know that writing boilerplate code like getters, setters, equals, hashCode & toString methods can be time-consuming & repetitive. It also clutters up the codebase with low-value code that's difficult to write & maintain. 

Lombok aims to solve this problem by generating this common code automatically at compile-time. With the help of Lombok annotations, you can significantly reduce the amount of code you need to write.

Let’s see some of the key reasons to use Lombok :

1. Less code to write: Lombok generates common methods, so you don't have to. This saves time & effort.
 

2. More readable code: By removing boilerplate, your classes become shorter & easier to read. The focus is on the important business logic.
 

3. Fewer bugs: Writing boilerplate code is error-prone. Lombok generates correct & consistent code, reducing the chance of bugs.
 

4. Easy to use: Lombok integrates with popular IDEs & build tools. Adding it to a project is straightforward.
 

5. Customizable: Lombok provides configuration options to tailor the generated code to your needs.

Features of Lombok Project

Lombok provides many useful annotations that generate common Java code. Some key features are:

1. `@Getter` and `@Setter`

   - The `@Getter` annotation automatically generates getter methods for all non-static fields in the class. It saves you from writing boilerplate code for accessing field values.

   - Similarly, the `@Setter` annotation generates setter methods for all non-static fields, allowing you to modify field values.

   - These annotations can be applied at the class level or individual field level.

Example:

     @Getter @Setter private String name;


Lombok will generate the following methods:

     public String getName() {
         return this.name;
     }
     
     public void setName(String name) {
         this.name = name;
     }

2. `@NoArgsConstructor` and `@AllArgsConstructor`

   - The `@NoArgsConstructor` annotation generates a constructor with no parameters. It allows you to create an instance of the class without providing any arguments.

   - The `@AllArgsConstructor` annotation generates a constructor that accepts all fields as parameters. It enables you to create an instance of the class by providing values for all fields.

   - These annotations eliminate the need to write constructors manually.

Example:

     @NoArgsConstructor
     @AllArgsConstructor
     public class Person {
         private String name;
         private int age;
     }


Lombok will generate the following constructors

     public Person() {
     }
     
     public Person(String name, int age) {
         this.name = name;
         this.age = age;
     }

3. `@ToString`

   - The `@ToString` annotation generates a `toString()` method that returns a string representation of the object. It includes all non-static fields by default.

   - This annotation saves you from writing the `toString()` method manually, which is often used for debugging or logging purposes.

Example

     @ToString
     public class Person {
         private String name;
         private int age;
     }

     Lombok will generate the following method:
     @Override
     public String toString() {
         return "Person(name=" + this.name + ", age=" + this.age + ")";
     }


These annotations significantly reduce the amount of boilerplate code you need to write. They generate the necessary methods at compile-time, making your code more concise and maintainable.

For example, consider the `Person` class with Lombok annotations

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person {
    private String name;
    private int age;
}


With just a few annotations, Lombok generates the getter and setter methods for `name` and `age` fields, a no-args constructor, a constructor accepting all fields, and a `toString()` method. You can use the generated methods like this:

Person person = new Person("Sinki", 28);
System.out.println(person.getName()); // Output: Sinki
person.setAge(29);
System.out.println(person); // Output: Person(name=Sinki, age=29)

4. `@Builder`

   - The `@Builder` annotation generates a builder pattern for the class. It allows you to create instances of the class using a step-by-step approach, which is particularly useful when dealing with classes that have many fields or when you want to create immutable objects.

   - When you annotate a class with `@Builder`, Lombok generates a nested builder class and methods to set the values of each field.
 

Example

     @Builder
     public class Person {
         private String name;
         private int age;
         private String email;
     }
  


Lombok will generate a builder class that you can use to create instances of `Person`:

Person person = Person.builder()
  .name("Ravi")
 .age(32)
  .email("ravi@example.com")
 .build();

    
 - The builder pattern provides a readable and flexible way to create objects, especially when you have optional fields or when you want to enforce certain constraints during object creation.

5. `@Data`

 - The `@Data` annotation is a convenient shortcut that combines several Lombok annotations into one. It is equivalent to using `@Getter`, `@Setter`, `@ToString`, `@EqualsAndHashCode`, and `@RequiredArgsConstructor` together.

   - When you annotate a class with `@Data`, Lombok generates getter and setter methods for all non-static fields, a `toString()` method, `equals()` and `hashCode()` methods based on the fields, and a constructor with required fields (i.e., final fields and fields annotated with `@NonNull`).

   - Example:

     @Data
     public class Person {
         private String name;
         private int age;
         private String email;
     }


Lombok will generate getter and setter methods for `name`, `age`, and `email` fields, a `toString()` method, `equals()` and `hashCode()` methods, and a constructor that accepts `name`, `age`, and `email` as parameters.

- The `@Data` annotation is a convenient way to quickly generate common methods for a class, reducing the amount of boilerplate code you need to write.

In addition to `@Builder` and `@Data`, Lombok provides many other useful annotations:

- `@Value`: Similar to `@Data`, but it creates immutable classes. It generates getter methods, `toString()`, `equals()`, and `hashCode()`, and a constructor with all fields.
 

- `@NonNull`: Indicates that a field must not be null. Lombok generates null checks in the constructor and setter methods.
 

- `@Cleanup`: Automatically closes resources (such as streams or database connections) after they are used, avoiding the need for explicit `try-finally` blocks.
 

- `@SneakyThrows`: Allows you to throw checked exceptions without declaring them in the method signature, reducing the need for explicit `throws` declarations.

Java Lombok Package

To use Lombok in your Java project, you need to add the Lombok package. 

Let’s see how you can do that: 

1. Maven Dependency

If you're using Maven, add the following dependency to your pom.xml file:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.24</version>
    <scope>provided</scope>
</dependency>

2. Gradle Dependency

For Gradle projects, add the following line to your build.gradle file:

compileOnly 'org.projectlombok:lombok:1.18.24'

3. Manual Installation

If you're not using a build tool, you can download the Lombok JAR file from the official website (https://projectlombok.org) & add it to your project's classpath.

Once you've added the Lombok dependency, you can start using Lombok annotations in your Java code. However, your IDE also needs to support Lombok. Many popular IDEs like Eclipse, IntelliJ IDEA & NetBeans have Lombok plugins that enable annotation processing.

For example, to install Lombok in Eclipse:

1. Download the Lombok JAR file.
 

2. Run the JAR file by double-clicking it. This will open an installer.
 

3. Specify the location of your Eclipse installation & click "Install/Update".
 

4. Restart Eclipse.


After installing the Lombok plugin, your IDE will recognize Lombok annotations & generate the appropriate code at compile-time.

Purpose to Use Lombok Project

The main purpose of using Lombok in Java projects is to reduce boilerplate code & make the codebase more concise & maintainable. Let’s see some other important reasons also, like :

1. Eliminate Repetitive Code: Writing getters, setters, equals, hashCode & toString methods for every class can be tedious & time-consuming. Lombok annotations generate this code automatically, saving developers time & effort.
 

2. Improve Code Readability: By removing the need for boilerplate code, Lombok makes Java classes shorter & easier to read. The focus is on the important business logic rather than repetitive method implementations.
 

3. Reduce Error-Prone Code: Writing boilerplate code is prone to errors. Developers might forget to update equals & hashCode methods when adding new fields, leading to bugs. Lombok generates correct & consistent code, reducing the chances of such errors.


4. Enhance Productivity: By eliminating the need to write & maintain boilerplate code, Lombok allows developers to focus on solving business problems. They can spend more time writing valuable code & less time on repetitive tasks.


5. Simplify Refactoring: When class fields change, the corresponding getters, setters, equals, hashCode & toString methods need to be updated. With Lombok, these updates are handled automatically, making refactoring easier & less error-prone.


6. Improve Code Consistency: Lombok generates code based on a consistent template. This ensures that all classes follow the same structure & style, improving code consistency across the project.

7. Facilitate Testing: Lombok annotations like @Builder make it easier to create objects for testing. Builders provide a step-by-step way to construct objects, which is particularly useful when dealing with complex classes.

Concise Data Object

One of the most common use cases for Lombok is creating concise data objects or POJOs (Plain Old Java Objects). For example : 

Without Lombok

public class User {
    private String firstName;
    private String lastName;
    private int age;
    public User() {
    }
    public User(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getAge() {
        return age;
    }


    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                ", age=" + age +
                '}';
    }
}

With Lombok

@Data
public class User {
    private String firstName;
    private String lastName;
    private int age;
}


By using the @Data annotation, Lombok generates the constructor, getters, setters & toString methods automatically. The resulting code is much shorter & more readable.

Here's how you can create & use a User object with Lombok:

User user = new User();
user.setFirstName("Rahul");
user.setLastName("Sharma");
user.setAge(25);

System.out.println(user);

 

Output

User(firstName=Rahul, lastName=Sharma, age=25)


As you can see, Lombok significantly reduces the amount of code needed to create a simple data object, making the code more concise & maintainable.

Generating Getters and Setters

Lombok provides the @Getter and @Setter annotations to automatically generate getter and setter methods for class fields. This eliminates the need to write these methods manually. 

For example : 

Without Lombok

public class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

With Lombok

public class Person {
    @Getter @Setter private String name;
    @Getter @Setter private int age;
}


By adding the @Getter and @Setter annotations to the fields, Lombok automatically generates the corresponding getter and setter methods. You can use these methods to access and modify the field values

Person person = new Person();
person.setName("Rinki");
person.setAge(30);

String name = person.getName();
int age = person.getAge();


Lombok also provides additional options for customizing the generated methods. For example, you can specify an access level for the methods using the AccessLevel parameter:


@Getter(AccessLevel.PROTECTED) @Setter(AccessLevel.PROTECTED) private String email;


In this case, Lombok will generate getter and setter methods with protected access level.


You can also use the @Getter and @Setter annotations at the class level to generate getters and setters for all non-static fields:

@Getter @Setter
public class Person {
    private String name;
    private int age;
}


This will generate getter and setter methods for both the name and age fields.

Configure Lombok in Eclipse IDE

To use Lombok in your Eclipse IDE, you need to install the Lombok plugin. 

Let’s discuss how to configure Lombok in Eclipse:

1. Download Lombok

   - Go to the Lombok website: https://projectlombok.org/download

   - Download the latest version of the Lombok JAR file.

Download page

2. Run the Lombok Installer

   - Double-click on the downloaded Lombok JAR file to run the installer.

   - If prompted, select the location of your Eclipse installation.

   - Click the "Install/Update" button to install Lombok in Eclipse.

   - Confirm the installation by clicking "OK" in the confirmation dialog
 

File

3. Restart Eclipse

   - After the installation is complete, restart Eclipse for the changes to take effect.

4. Enable Annotation Processing

   - In Eclipse, go to "Window" > "Preferences".

   - Navigate to "Java" > "Compiler" > "Annotation Processing".

   - Check the "Enable project specific settings" checkbox.

   - Check the "Enable annotation processing" checkbox.

   - Click "Apply and Close".

 Enable Annotation Processing
4. Enable Annotation Processing

5. Add Lombok to the Project:

   - Right-click on your project in the Eclipse Project Explorer.

   - Select "Properties" from the context menu.

   - Go to "Java Build Path" > "Libraries".

   - Click on the "Add External JARs" button.

   - Browse and select the Lombok JAR file you downloaded earlier.

   - Click "Apply and Close".

Add Lombok to the Project:

6. Use Lombok Annotations

   - In your Java code, you can now use Lombok annotations like `@Getter`, `@Setter`, `@ToString`, etc.

   - Eclipse will automatically recognize these annotations & generate the corresponding code at compile-time.


For example 

import lombok.Getter;
import lombok.Setter;

public class User {
    @Getter @Setter private String username;
    @Getter @Setter private String email;
}

Java Program without Using Lombok

Before diving into how Lombok simplifies Java code, let's take a look at a Java program without using Lombok. Consider a simple `Person` class with a few fields & methods:

  • Java

Java

public class Person {
private String name;
private int age;

public Person() {
}

public Person(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

public class Main {
public static void main(String[] args) {
Person person = new Person("Harsh", 25);
System.out.println(person);

person.setAge(26);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
You can also try this code with Online Java Compiler
Run Code


In this example, we have a `Person` class with `name` & `age` fields. We manually defined a no-args constructor, a parameterized constructor, getter & setter methods for each field & a `toString()` method.
Output

Person{name='Harsh', age=25}
Name: Harsh
Age: 26


As you can see, writing all the boilerplate code for constructors, getters, setters & toString() can be difficult & repetitive, especially for classes with many fields.

Java Program with Lombok

Now let's see how Lombok can simplify the previous Java program. We'll use Lombok annotations to generate the boilerplate code automatically.

Let’s see the `Person` class rewritten using Lombok:

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person {
    private String name;
    private int age;
}


In this version, we've added Lombok annotations to the class:

- `@Getter` generates getter methods for all fields.
 

- `@Setter` generates setter methods for all fields.
 

- `@NoArgsConstructor` generates a no-args constructor.
 

- `@AllArgsConstructor` generates a constructor with all fields as parameters.
 

- `@ToString` generates a `toString()` method that includes all fields.


With these annotations, Lombok generates all the necessary methods at compile-time. We no longer need to write them manually.

Using the Lombok-enhanced `Person` class in a Java program remains the same:

  • Java

Java

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Person {
private String name;
private int age;
}
public class Main {
public static void main(String[] args) {
Person person = new Person("Sanjana", 30);
System.out.println(person);

person.setAge(31);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
You can also try this code with Online Java Compiler
Run Code


Output

Person(name=Sanjana, age=30)
Name: Sanjana
Age: 31


The program behaves the same as before, but the `Person` class is much more concise & readable. Lombok takes care of generating the boilerplate code, allowing us to focus on the essential fields & logic.

Note: This is just a simple example, but Lombok's annotations can be used in more complex scenarios to greatly reduce the amount of repetitive code we need to write.

Frequently Asked Questions

Does Lombok work with all Java versions?

Lombok supports Java 6 & above. It is compatible with most modern Java versions.

Can Lombok be used with other libraries & frameworks?

Yes, Lombok integrates well with popular libraries & frameworks like Spring, Hibernate & JPA.

Are there any performance impacts when using Lombok?

No, Lombok does not impact performance. The generated code is equivalent to hand-written code.

Conclusion

In this article, we explained Lombok, a powerful Java library that helps reduce boilerplate code. We learned about Lombok's key features, such as @Getter, @Setter, @ToString, @EqualsAndHashCode, @Data & @Builder, which automatically generate common methods. We saw how Lombok makes Java classes more concise, readable & maintainable by eliminating the need to write repetitive code.

You can also checkout our other blogs on Code360

Live masterclass