@Builder.Default in base class not working?

Feihua Fang :

I'm writing classes with lombok annotations and got a problem:

@AllArgsConstructor
@Data
public abstract class Base {
    protected static final int a = 1;
    @Builder.default
    protected int b = 1;
}

public static class Sub extends Base {
    @Builder
    Sub(final int b, final int c) {
        super(b);
        this.c = c;
    }
    private int c;
}

And @Builder.default is not working when I trying to build a Sub class like this:

Sub.builder()
   .c(100)

b is supposed to be default value 1, but actually it is null.

I found some cases which might be related to mine. It seems that super() is incompatible with @Builder.Default. I still don't know how to make b not null. Anyone can help? Thanks!

Jan Rieke :

@Builder is not working well with inheritance, because there are technical limitations what annotation processors like Lombok can do. Due to these limitations, Lombok cannot establish the link between the name of the parameter and the name of the field in the superclass. (And it is also conceptually difficult to do this, because you could name the parameter differently, and then you'd have to do some deeper code analysis.)

If you are OK with using experimental features, you could give @SuperBuilder a try. Add it on both classes, and remove the manual constructor. (Note that @SuperBuilder is not yet supported in IntelliJ.)

The alternative is also using a manual constructor in the superclass and set the default there.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=134635&siteId=1