Lombok – Reduce Boilerplate in Java
Writing boilerplate code in Java — like getters, setters, constructors, and builders — can get repetitive. Project Lombok simplifies this with annotations that auto-generate code at compile-time, keeping your classes clean and focused.
🔧 Setup
To use Lombok, add this dependency to your project:
➡️ Maven
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> <scope>provided</scope> </dependency>
➡️ Gradle
compileOnly 'org.projectlombok:lombok:1.18.30' annotationProcessor 'org.projectlombok:lombok:1.18.30'
📦 Example Without Lombok
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; }
}
That's a lot of code for just a data class!
✅ Same Class With Lombok
import lombok.Data;
@Data
public class User {
private String name;
private int age;
}
Done! @Data includes @Getter, @Setter, @ToString, @EqualsAndHashCode, and @RequiredArgsConstructor.
🎯 Common Lombok Annotations
@Getterand@Setter– generates getters/setters@ToString– generates atoString()method@EqualsAndHashCode– addsequals()andhashCode()@NoArgsConstructor,@AllArgsConstructor– constructors@Builder– fluent builder API@Value– makes an immutable class (like Kotlin’sdata class)
🚀 Builder Example
@Builder
public class Product {
private String name;
private double price;
}
// Usage
Product p = Product.builder()
.name("Laptop")
.price(1200.0)
.build();
🛠 IDE Support
Lombok works in IntelliJ IDEA and Eclipse, but you may need to:
- Install the Lombok plugin
- Enable annotation processing in your IDE settings
📌 Conclusion
Lombok is a fantastic tool for reducing repetitive Java code. Use it wisely to simplify your codebase, but be sure your team understands what’s being auto-generated under the hood.
Comments
Post a Comment