Search code examples
javaconstructorhierarchylombokbuilder

Lombok @SuperBuilder hide parent fields


I have the following classes

The first level of hierarchy:

abstract class Parent2 {

    private P2_Param1 p2_param1;
    private P2_Param2 p2_param2;

    protected Parent2(P1_Param1 p1_param1) {
        p2_param1 = p1_param1.something()
        p2_param2 = p1_param1.somethingElse()
    }
}

Second level:

abstract class Parent1 extends Parent2 {

    private P1_Param1 p1_param1;

    protected Parent1(P1_Param1 p1_param1) {
        super(p1_param1);
        this.p1_param1 = p1_param1;
    }
}

And hundreds of classes that look like this:

class Child extends Parent1 {

    private C_Param1 c_param1;
    private C_Param2 c_param2;
    private C_Param3 c_param3;
    private C_Param4 c_param4;
    // ... many more parameters here

    public Child(P1_Param1 p1_param1) {
        super(p1_param1);
    }
}

These classes were used like this for a long time - child fields were used only to represent schema.

Now things changed and Child fields need to hold values. I'd like to create as few changes in ChildX classes as possible and avoid implementing constructors that take all child parameters + p1_param1. Ideally, it'd be great to use Lombok annotations or add some code in the parent classes.

I was thinking about instantiating the child class as it was before and using toBuilder = true to copy and fill values:

var child = new Child(p1_param1)
        .toBuilder()
        .c_param1(c_param1)
        .build();

I tried to use the @SuperBuilder(toBuilder = true) annotation, but now I have an access to fill fields from parent classes (e.g. p2_param2) and I would like to avoid that.

Is my approach valid? Can I somehow make the parent fields not accessible via public child builder methods?


Solution

  • I found a solution to my question:

    The answer is to use the Delombok option and then remove all methods from the generated (@SuperBuilder) parents' builders.