How to use Lombok @Builder annotation on Methods

user3139545 picture user3139545 · Apr 28, 2016 · Viewed 57.4k times · Source

I want to have an easy way to construct test data and have found the Builder pattern to be a good fit as described here. However to reduce boilerplate codes in the component tests, even more, I have found @Builder from Project Lombok to be a nice candidate to try. However, I can't find any documentation or online examples on how to use it on a method. I want to use @Builder on some sort of factory method since I can't make any changes to the implementation.

Can someone give an example on how to actually use @Builder on a method?

Answer

Deendayal Garg picture Deendayal Garg · Apr 28, 2016

This is how you use @Builder.

//Employee.Java
import lombok.Builder;
import lombok.ToString;

@Builder
@ToString
public class Employee {
   private final String empName;
   private final int salary;
}

//   Main.java

public class Main {

public static void main(String[] args) {
    Employee emp = Employee.builder().empName("Deendaya").salary(100).build();
    System.out.println(emp);
  }
}