Latest Posts

LOMBOK :: Boilerplate Killer

Project Lombok is a increasingly popular Java library (a compile time plugin) which helps developers avoid writing boiler plate code (e.g. Getters, Setters, Constructors etc.). This annotation based java library has been quite popular in addressing the verbosity criticism Java has been receiving for quite sometime.


It easily plugs itself with the IDE and build tools thereby facilitating generation of boilerplate code at compile time. The outcome of which is a piece of code which is much cleaner and legible.

Installation is quite straightforward - Just add lombok dependency for the relevant project (i.e. POM.xml).

Lets have a look at some widely used annotations and their sample implementation.

public class Employee {

 private String firstName;
 private String lastName;
 private String deptName;
 private String designation;

@Getter / @Setter - We can annotate a particular field or an entire Class. Lombok will generate default getter / setter. By default these methods will have access level as public. This behavior can be overridden by explicitly specifying an AccessLevel. (see example below)
 private String firstName;

@ToString - A class definition can be annotated with this annotation. It prints the class name followed by all non static fields in order, separated by commas. Option "includeFieldNames" by default is true and ensures fields are printed too. Option "exclude" comes to rescue if we need to skip some fields.

@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor - Constructors made to order: Generates constructors that take no arguments, one argument per final / non-null field, or one argument for every field.

@Data - This is a very convenient annotation which bundles the features of @Getter / @Setter, @ToString, @EqualAndHascode & @RequiredArgsConstructor

No comments:

Post a Comment