Is it possible to make Lombok’s builder public?

@Builder already produces public methods, it’s just the constructor that’s package-private. The reason is that they intend for you to use the static builder() method, which is public, instead of using the constructor directly:

Foo foo = Foo.builder()
    .property("hello, world")
    .build();

If you really, really, really want the constructor to be public (there seems to be some suggestion that other reflection-based libraries might require it), then Lombok will never override anything that you’ve already declared explicitly, so you can declare a skeleton like this with a public constructor and Lombok will fill in the rest, without changing the constructor to package-private or anything.

@Builder
public class Foo
{
    private final String property;

    public static class FooBuilder
    {
        public FooBuilder() { }

        // Lombok will fill in the fields and methods
    }
}

This general strategy of allowing partial implementations to override default behaviour applies to most (maybe all) other Lombok annotations too. If your class is annotated with @ToString but you already declared a toString method, it will leave yours alone.

Just to show you everything that gets generated, I wrote the following class:

@Builder
public class Foo
{
    private final String property;
}

I then ran it through delombok to see everything that was generated. As you can see, everything is public:

public class Foo
{
    private final String property;

    @java.beans.ConstructorProperties({"property"})
    Foo(final String property) {
        this.property = property;
    }

    public static FooBuilder builder() {
        return new FooBuilder();
    }

    public static class FooBuilder
    {
        private String property;

        FooBuilder() { }

        public FooBuilder property(final String property) {
            this.property = property;
            return this;
        }

        public Foo build() {
            return new Foo(property);
        }

        public String toString() {
            return "Foo.FooBuilder(property=" + this.property + ")";
        }
    }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)