Introduction to Project Lombok
Quick Run through annotations and get started with Lombok
Join the DZone community and get the full member experience.Join For Free
Writing a new Model/Data comes with the addition of a lot of boiler plate code. Boiler plate code is the code that is repetitive throughout application and has little change in its implementation.
The common step in creating new POJO or Model class is writing Getters, Setters, Constructors, To String methods, Equals method, etc. Even if the IDEs offer to generate them for the user, it still doesn't decrease the amount of repetitive code that goes in these methods.
Lombok is armed with annotations that take care of boiler plate code.
Val- Creates a local variable with val which will be initialized based on initialization expression. The local variable will also be made final.
Var- Works exactly like Val but the local variable is not declared final.
@Setter- Add setter for all variables.
@Getter- Add getter for all the variables.
@RequiredArgsConstructor- Generates constructor for each field.
@NoArgsConstructor- Creates a non-parametrized constructor.
@AllArgsConstructor- Creates a parametrized constructor containing all fields.
@ToString- Creates toString method.
@EqualsAndHashCode- Creates Equals and Hashcode implementation for fields in the class.
@Value- Short for final @ToString @EqualsAndHashCode @AllArgsConstructor @FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) @Getter.
@Data- It is a quick way of combining features of @ToString, @EqualsAndHashCode, @Getter, @Setter and @RequiredArgsConstructor.
@Builder- Makes instantiation of class easier and provides a way to statically initialize fields in a class.
@NotNull- Makes sure the value of object is not null. This is highly beneficial when dealing with data access object and saves risk NullPointerException that may go unchecked.
As shown in example a lot of code is reduced using Lombok annotations giving user a cleaner code.
Set Up Lombok
Get the latest Lombok Jar from https://projectlombok.org/download.html.
If the exe file is not executed on click run
java -jar lombok.jar at location of the downloaded jar file. Select/Verify your IDE location and install.
Restart your IDE after installation.
Even after installing the Jar, it is necessary to specify the jar in dependencies.
For Manually adding the Jar:
Right Click On Project -> Properties -> Java Build Path -> Libraries -> Add External Jars.. -> Select the Downloaded Jar -> Apply
Opinions expressed by DZone contributors are their own.