Using Lombok in Java | Generated by AI

Home PDF

To use Lombok in Java, you’ll need to set it up in your project to simplify your code by reducing boilerplate, like getters, setters, and constructors. Here’s how you can do it step-by-step:

First, you need to add Lombok as a dependency. If you’re using Maven, include this in your pom.xml:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.32</version> <!-- Check for the latest version -->
    <scope>provided</scope>
</dependency>

For Gradle, add this to your build.gradle:

provided 'org.projectlombok:lombok:1.18.32'
// Also add this to ensure annotation processing works
annotationProcessor 'org.projectlombok:lombok:1.18.32'

Next, if you’re using an IDE like IntelliJ IDEA or Eclipse, you’ll need to enable annotation processing and install the Lombok plugin:

Now, you can start using Lombok annotations in your Java code. Here’s a simple example:

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

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

In this example:

When you compile or run this, Lombok processes these annotations and adds the boilerplate code for you. You can test it like this:

public class Main {
    public static void main(String[] args) {
        Person person = new Person("Alice", 30);
        System.out.println(person.getName()); // Outputs: Alice
        person.setAge(31);
        System.out.println(person.getAge()); // Outputs: 31
    }
}

A few popular annotations you might also find useful:

For example, with @Data and @Builder:

import lombok.Data;
import lombok.Builder;

@Data
@Builder
public class User {
    private String username;
    private String email;
}

// Usage
public class Main {
    public static void main(String[] args) {
        User user = User.builder()
                        .username("john_doe")
                        .email("john@example.com")
                        .build();
        System.out.println(user); // Outputs: User(username=john_doe, email=john@example.com)
    }
}

Keep in mind:


Back 2025.02.27 Donate