简体   繁体   中英

How to override lombok builder method

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM