There are many issues with writing boilerplate code: It’s hard to identify code that deviates from normal, it adds visual complexity to a file, and it’s not fun to write. Unfortunately in Java there are constructors, getters, and setters that need to be written for almost any class.
Lombok provides a cleaner interface for adding these functions with annotations. When you add an annotation to your Java class, Lombok will generate code for you behind the scenes.
Getters and Setters
You can instruct Lombok to create getters and setters by adding a
@Setter annotation on the private field. This is equivalent to writing out those methods yourself.
Lombok will prevent you from creating a setter for a final field.
If you want to add null checks where appropriate, you can do so with the
@NonNull annotation. Lombok then will add null checks where appropriate and throw a null pointer exception if a null is passed.
Lombok provides three annotations for creating a constructor for a class. These can be used simultaneously to create multiple constructors if desired.
@NoArgsConstructor – Creates a constructor with no arguments. This will result in a compiler error if not possible due to final fields.
@RequiredArgsConstructor – Creates a constructor with arguments for required (final, or non initialized
@AllArgsConstructor – Creates a constructor with arguments for all fields.
Other Utility Methods
Quite frequently when writing a class you’ll want a toString method to help debug and equals and hashCode methods to better support object equality. Implementing these methods by hand can be burdensome, and if done incorrectly may lead to bugs. Luckily Lombok provides
@EqualsAndHashCode annotations to auto generate these functions.
Tying it all together
With the annotations mentioned above, you may end up with a class that looks like this fairly often.
The developers of Lombok realized this combination of annotations is fairly common together, so they provided a
@Data annotation that does all of this for you!
Lombok offers annotations that reduce the amount of boilerplate code that needs to be for your Java classes. For more information you can find the Lombok documentation here.