What is Lombok?
Lombok is a Java library that helps reduce boilerplate code—the repetitive code you often write in Java, like getters, setters, constructors, toString(), hashCode(), etc.
It does this through annotations that are processed at compile-time, so the generated code doesn’t appear in your source files but is present in the compiled bytecode.
Why use Lombok?
Java is verbose, and many classes contain repetitive code. For example:
public class User {
private String name;
private int age;
public User() {}
public User(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 "User{name='" + name + "', age=" + age + "}";
}
}
This is a lot of repetitive code! Lombok can replace all of this with just annotations:
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private String name;
private int age;
}
✅ Same functionality, way less code.
Common Lombok Annotations
| Annotation | Purpose |
|---|---|
@Getter | Generates getters for all fields |
@Setter | Generates setters for all fields |
@ToString | Generates toString() method |
@EqualsAndHashCode | Generates equals() and hashCode() |
@NoArgsConstructor | Generates a no-argument constructor |
@AllArgsConstructor | Generates a constructor with all fields |
@RequiredArgsConstructor | Generates a constructor for final or @NonNull fields |
@Data | Shortcut for @Getter, @Setter, @ToString, @EqualsAndHashCode, and @RequiredArgsConstructor |
@Builder | Implements the Builder pattern |
@Slf4j | Adds a logger (private static final Logger log = LoggerFactory.getLogger(ClassName.class)) |
Example with @Builder
import lombok.Builder;
import lombok.ToString;
@Builder
@ToString
public class Car {
private String make;
private String model;
private int year;
}
// Usage
public class Main {
public static void main(String[] args) {
Car car = Car.builder()
.make("Toyota")
.model("Camry")
.year(2025)
.build();
System.out.println(car);
}
}
Output:
Car(make=Toyota, model=Camry, year=2025)
Key Points
- Lombok reduces boilerplate code.
- Annotations are processed at compile-time, so they don’t affect runtime performance.
- Works best for POJOs, DTOs, and entities.
- Overusing Lombok can sometimes hide code; know what is generated.
