How to make private builder() method with lombok

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

}

Tags:

Java

Lombok