I’m using lombok @Builder. When I place @Builder
annotation on the MyExample
class, @Builder
generates public builder()
method. But I want to make private builder()
method. Unfortunately @Builder
annotation does not have access
option. How should I do?
By using the @Builder annotation, you let Lombok generate the builders for you. By annotating a class with @Builder , Lombok will produce a class implementing the aforementioned builder pattern. For example, by annotating the Author class, an AuthorBuilder class will be automatically generated.
Project Lombok's @Builder is a helpful mechanism for using the Builder pattern without writing boilerplate code. We can apply this annotation to a Class or a method. In this quick tutorial, we'll look at the different use cases for @Builder.
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()
The @SuperBuilder annotation produces complex builder APIs for your classes. In contrast to @Builder , @SuperBuilder also works with fields from superclasses. However, it only works for types. Most importantly, it requires that all superclasses also have the @SuperBuilder annotation.
You can overwrite the generated builder method to make it private. As far as I know, that's the only way:
@Builder
public static class Foo<F, T> {
// hide lombok's builder method:
private static FooBuilder builder() {
return new FooBuilder();
}
}
However, this enables you to do some more advanced initialization of the builder. For example, you can initialize the builder with some defaults and also kickstart the builder with initial user-supplied values.
Here's an example:
@Builder
public static class Car {
// kickstart builder method available to user
public static CarBuilder builder(String brand, String model) {
return builder().brand(brand).model(model);
}
// hide lombok's own builder method and apply some defaults:
private static CarBuilder builder() {
return new CarBuilder().color(System.getenv("DEFAULT_CAR_COLOR"));
}
}
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