Lombok @Builder继承如何同时支持父类与子类构建?
Absolutely, Lombok can handle scenarios where both a parent class and its child need their own functional @Builder implementations—you just need to use the right approach to avoid the method conflict you're encountering.
Recommended Approach: Use @SuperBuilder (Lombok 1.18.4+)
Lombok introduced the @SuperBuilder annotation specifically to solve inheritance-related Builder issues. It automatically handles parent class properties in the child's Builder, and lets both classes have their own independent Builder APIs.
Step-by-Step Implementation
- Add
@SuperBuilderto your parent class:
@SuperBuilder public class Parent { private final String parentProperty; }
- Add
@SuperBuilderto your child class (which extends the parent):
@SuperBuilder public class Child extends Parent { private final String childProperty; }
Usage Examples
- Build an instance of the parent class:
Parent parent = Parent.builder() .parentProperty("Parent value") .build();
- Build an instance of the child class (with access to both parent and child properties):
Child child = Child.builder() .parentProperty("Parent value") .childProperty("Child value") .build();
This approach is clean, maintainable, and avoids all manual workaround code.
Legacy Workaround (For Lombok Versions <1.18.4)
If you're stuck on an older Lombok version that doesn't support @SuperBuilder, you can resolve the method name conflict by renaming the child class's Builder method, and explicitly include parent properties in the child's Builder.
Implementation
- Add
@Builderto the parent class as usual:
@Builder @AllArgsConstructor public class Parent { protected String parentProperty; }
- For the child class, use
builderMethodNameto rename its Builder method (to avoid conflicting with the parent'sbuilder()), and add@AllArgsConstructorto ensure the child's constructor includes parent properties:
@Builder(builderMethodName = "childBuilder") @AllArgsConstructor public class Child extends Parent { private String childProperty; }
Usage Examples
- Build a parent instance:
Parent parent = Parent.builder() .parentProperty("Parent value") .build();
- Build a child instance using the renamed Builder method:
Child child = Child.childBuilder() .parentProperty("Parent value") .childProperty("Child value") .build();
While this works, it's less elegant than @SuperBuilder and requires more manual setup.
内容的提问来源于stack exchange,提问作者IgorGudkov

