Home > Software engineering >  How to override lombok builder method
How to override lombok builder method

Time:12-15

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

CodePudding user response:

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

CodePudding user response:

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);
  }
}
  • Related