Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override lombok builder method

Tags:

java

lombok

I want to override Lombok default builder method. I tried this piece of code, but it doesn't work.

Is it even possible to do such thing?

@Data
@Builder
static class A {
    private int a;

    static class Builder {
        A.ABuilder a(int x) {
            this.a = 2 * x;
            return this;
        }
    }

}

private static void fun() {
    var a = A.builder()
            .a(1)
            .build();
}

enter image description here

like image 248
Stepan Kryzhankov Avatar asked Dec 01 '25 12:12

Stepan Kryzhankov


1 Answers

The builder name you've created must match with the default one created by Lombok.

This would work,

public static class ABuilder {
    ABuilder a(int x) {
        this.a = 2 * x;
        return this;
    }
}

More details - Use custom setter in Lombok's builder

For some reason, if you want to name the Builder class differently, use builderClassName of the Builder annotation.

@Data
@Builder (builderClassName = "MyBuilderClass")
static class A {
    private int a;

    static class MyBuilderClass {
        MyBuilderClass a(int x) {
            this.a = 2 * x;
            return this;
        }
    }
}
like image 192
user7 Avatar answered Dec 03 '25 02:12

user7



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!