How to override Builder methods of Lombok in Java

What is Lombok?

Lombok is a Java library that auto generates lots of boiler plate code for Java classes. Lombok works at compile time and manipulates Java byte code to add additional features. Lombok uses annotations to specify what boiler plate code will be generates. Eg. @Getter annotation can be applied to any Java bean to auto generate Getter methods for all the fields in that bean.

In this article we will be looking at the Builder annotation of Lombok.

What is Builder annotation in Lombok?

Lombok can be used to generate Builder class for a Java bean, by annotating the bean class with @Builder annotation. 

Many times we might want to override some of the auto generated methods in our Builder class, to support specific functionality. For example, in below Pet class we are overriding the type() method in Builder so that it can accept String parameter instead of PetType parameter.

We are achieving this by providing implementation of portion of Builder class that we want to override, rest of the class is still generated by Lombok, for us.

Pet object class with overridden Builder annotation.

Usage of overridden Build in service class.

0 comments:

Post a Comment