Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Builder.Default in base class not working?

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!

like image 338
Feihua Fang Avatar asked Sep 05 '25 03:09

Feihua Fang


1 Answers

@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.

like image 143
Jan Rieke Avatar answered Sep 07 '25 23:09

Jan Rieke