Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required arguments with a Lombok @Builder

Tags:

java

lombok

If I add @Builder to a class. The builder method is created.

Person.builder().name("john").surname("Smith").build(); 

I have a requirement where a particular field is required. In this case, the name field is required but the surname is not. Ideally, I would like to declare it like so.

Person.builder("john").surname("Smith").build() 

I can't work out how to do this. I have tried adding the @Builder to a constructor but it didn't work.

@Builder public Person(String name) {     this.name = name; } 
like image 363
jax Avatar asked Apr 27 '15 00:04

jax


People also ask

What is @builder annotation in Lombok?

Lombok's @Builder annotation is a useful technique to implement the builder pattern that aims to reduce the boilerplate code. In this tutorial, we will learn to apply @Builder to a class and other useful features. Ensure you have included Lombok in the project and installed Lombok support in the IDE.

What does @builder do in Lombok?

When we annotate a class with @Builder, Lombok creates a builder for all instance fields in that class. We've put the @Builder annotation on the class without any customization. Lombok creates an inner static builder class named as StudentBuilder. This builder class handles the initialization of all fields in Student.

What is the use of @builder annotation in spring boot?

The @Builder annotation produces complex builder APIs for your classes. @Builder lets you automatically produce the code required to have your class be instantiable with code such as: Person. builder()

What is required args constructor?

@RequiredArgsConstructor generates a constructor with 1 parameter for each field that requires special handling. All non-initialized final fields get a parameter, as well as any fields that are marked as @NonNull that aren't initialized where they are declared.


1 Answers

You can do it easily with Lombok annotation configuration

import lombok.Builder; import lombok.ToString;  @Builder(builderMethodName = "hiddenBuilder") @ToString public class Person {      private String name;     private String surname;      public static PersonBuilder builder(String name) {         return hiddenBuilder().name(name);     } } 

And then use it like that

Person p = Person.builder("Name").surname("Surname").build(); System.out.println(p); 

Of course @ToString is optional here.

like image 179
Pawel Avatar answered Oct 13 '22 04:10

Pawel