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

如何基于Lombok @SuperBuilder实现泛型父类的子类实例构建

解决Lombok @SuperBuilder下父类统一构建子类实例的问题

核心问题原因

你原来的T.builder()写法无效,是因为泛型类型擦除导致编译器无法确认子类T存在静态builder()方法,而且Lombok为每个子类生成的builder()是独立静态方法,并非继承自Parent类,所以父类无法直接通过泛型调用子类的构建器。

重构方案:父类封装公共逻辑,子类传递定制逻辑

下面是具体的实现步骤和代码示例:


1. 基础类配置(确保Lombok注解正确)

首先保证父类和所有子类都添加@SuperBuilder注解,父类属性设为protected,让子类构建器能访问:

import lombok.SuperBuilder;

@SuperBuilder
public class Parent {
    protected int parentVariable; // 公共属性
}

子类示例(ChildA):

import lombok.SuperBuilder;

@SuperBuilder
public class ChildA extends Parent {
    private String childAVariable; // 子类独有属性
}

2. 父类封装公共构建逻辑

在Parent类中添加泛型方法,接收两个参数:

  • Supplier<B>:提供子类的构建器实例
  • Consumer<B>:用于设置子类的独有属性

方法内部先处理公共属性,再执行子类定制逻辑,最后构建实例:

import lombok.SuperBuilder;
import java.util.function.Consumer;
import java.util.function.Supplier;

@SuperBuilder
public class Parent {
    protected int parentVariable;

    // 公共构建方法:封装父类属性设置,子类传递定制逻辑
    protected <T extends Parent, B extends ParentBuilder<B, T>> T buildResponse(
            Supplier<B> builderSupplier,
            Consumer<B> childCustomizer
    ) {
        B builder = builderSupplier.get();
        // 设置父类公共属性
        builder.parentVariable(1);
        // 执行子类独有属性的定制逻辑
        childCustomizer.accept(builder);
        // 构建并返回子类实例
        return builder.build();
    }
}

3. 子类调用父类方法,传递定制逻辑

子类的buildResponse方法只需调用父类方法,传入自己的构建器和独有属性设置逻辑即可,无需重复写公共属性的代码:

import lombok.SuperBuilder;

@SuperBuilder
public class ChildA extends Parent {
    private String childAVariable;

    public ChildA buildResponse(String customChildValue) {
        return super.buildResponse(
                // 传递子类构建器
                ChildA::builder,
                // 设置子类独有属性
                builder -> builder.childAVariable(customChildValue)
        );
    }
}

方案优势

  • 父类统一维护公共属性的设置逻辑,彻底消除子类重复代码
  • 子类只需关注自身独有属性的定制,符合单一职责原则
  • 利用函数式接口传递逻辑,保持代码简洁且灵活

内容的提问来源于stack exchange,提问作者DashwoodIce9

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 06:35:02