You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Lombok @Builder继承如何同时支持父类与子类构建?

Handling Lombok @Builder for Both Parent and Child Classes

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.

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

  1. Add @SuperBuilder to your parent class:
@SuperBuilder
public class Parent {
    private final String parentProperty;
}
  1. Add @SuperBuilder to 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

  1. Add @Builder to the parent class as usual:
@Builder
@AllArgsConstructor
public class Parent {
    protected String parentProperty;
}
  1. For the child class, use builderMethodName to rename its Builder method (to avoid conflicting with the parent's builder()), and add @AllArgsConstructor to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:49:33