Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make private builder() method with lombok

Tags:

java

lombok

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?

like image 808
cgtdnpck Avatar asked Mar 01 '18 08:03

cgtdnpck


People also ask

How does Lombok generate builder?

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.

What is use of @builder in Lombok?

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.

What is the use of @builder annotation in Java?

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 difference between @builder and @SuperBuilder?

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.


1 Answers

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"));
    }

}
like image 191
Benny Bottema Avatar answered Sep 20 '22 15:09

Benny Bottema