0

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

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Read this. https://rusyasoft.github.io/java,%20lombok/2020/02/14/Overriding-build-setter-lombok-builder/ – Rashmi Shehana Dec 14 '22 at 14:57
  • Does this answer your question? [Use custom setter in Lombok's builder](https://stackoverflow.com/questions/42379899/use-custom-setter-in-lomboks-builder) – Thiyagu Dec 14 '22 at 14:57

2 Answers2

5

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;
        }
    }
}
Thiyagu
  • 17,362
  • 5
  • 42
  • 79
1

Try this

@Data
@Builder
public class A {
    private int a;
    private int b;

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

  public static void main(String[] args) {
      A aObj = A.builder().a(4).b(10).build();
    System.out.println(aObj);
  }
}
Sachin
  • 103
  • 2
  • 8