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; }
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.
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.
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()
@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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With