简体   繁体   中英

Lombok @Builder inheritance simultaneously working for parent and child

I have read this this post about using lombok @Bulider with inheritance https://reinhard.codes/2015/09/16/lomboks-builder-annotation-and-inheritance/ All works good. But in my case I need also use builder for Parent class , and this workaround doesn`t work.

I tried add @Builder to Parent class also but got Compilation failure because Child class try to override builder() method from Parent.

        @AllArgsConstructor
        public class Parent {

            private final long a;
            private final long b;
            private final double c;
        }

        public class Child extends Parent{

            private final long aa;
            private final long bb;
            private final double cc;
            @Builder
            public Child(long a, long b, long c,
                        long aa, long bb, long cc)
                super(a,b,c);
                this.aa = aa;
                this.bb = bb;
                this.cc =cc;
         }

I need both case builder like:

Parent.builder().a(10).b(20).build();
Child.builder().a(10).aa(20).bb(100).build();

Does lombok can handle that case?

Lombok try to override builder() method from Parent class in Child. So I tried to set not default name to builder method.

@Builder(builderMethodName = "parentBuilder")
@AllArgsConstructor
public class Parent {

    private final long a;
    private final long b;
    private final double c;
}

public class Child extends Parent{

    private final long aa;
    private final long bb;
    private final double cc;

    @Builder(builderMethodName = "childBuilder")
    public Child(long a, long b, long c,
                long aa, long bb, long cc)
        super(a,b,c);
        this.aa = aa;
        this.bb = bb;
        this.cc =cc;
 }

That works for me.

Lombok has introduced experimental features with version: 1.18.2 for inheritance issues faced with Builder annotation, and can be resolved with @SuperBuilder annotation as below.

@SuperBuilder
public class ParentClass {
    private final String a;
    private final String b;
}

@SuperBuilder
public class ChildClass extends ParentClass{
    private final String c;
}

Now, one can use Builder class as below (that was not possible with @Builder annotation)

ChildClass.builder().a("testA").b("testB").c("testC").build();

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