Builder Pattern with Project Lombok

Normally, when we need to create an object with a lot of its information, we can use the Builder Pattern for that purpose.

For example, I have a Student class as below:

To build this object with all information using the Builder Pattern, we need to create a Builder class as below:

Then, we can use this StudentBuilder object to create a new Student object as below:

Result:

Builder Pattern with Project Lombok

With Project Lombok, we have an easy way to create the Builder object by using @Builder annotation as below:

Using @Builder annotation, when generating the class, a new Builder class will be added. With above example, if you check the Student class in folder /target/classes/com/huongdanjava/lombok, you will see the content as below:

You can see the new Student.StudentBuilder class was added.

Now, you can use the StudentBuilder class as below:

Result:

Builder Pattern with Project Lombok

1/5 - (1 vote)

Add Comment