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

使用Lombok Builder模式时如何添加额外自定义构造方法

实现方案

你可以根据是否需要新构造支持Builder调用,选择以下两种方案:

方案1:直接新增自定义构造(最简单,无侵入原有逻辑)

直接在类中新增目标构造方法即可,原有Lombok注解无需调整,注意手动处理默认字段的赋值:

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Foo {
    private String message;
    private Integer status;
        
    @Builder.Default
    private LocalDateTime timestamp = LocalDateTime.now();

    // 新增自定义构造方法
    public Foo(Exception exception, Integer status) {
        this.message = exception.getMessage();
        this.status = status;
        // 必须手动赋值默认字段,@Builder.Default不会处理自定义构造的默认值
        this.timestamp = LocalDateTime.now();
    }
}

说明:

  • 原有全参、无参构造、类Builder功能完全不受影响,可正常使用
  • 新构造调用方式:new Foo(new RuntimeException("出错了"), 500)

方案2:新构造也支持Builder调用

如果你希望异常入参的构造也支持Builder模式调用,需要将类上的@Builder拆分到构造方法上,通过指定不同的builder方法名避免冲突:

@Data
@NoArgsConstructor
public class Foo {
    private String message;
    private Integer status;
        
    private LocalDateTime timestamp = LocalDateTime.now();

    // 原有全参构造,配置专属Builder方法名
    @Builder(builderMethodName = "normalBuilder")
    public Foo(String message, Integer status, LocalDateTime timestamp) {
        this.message = message;
        this.status = status;
        this.timestamp = timestamp == null ? LocalDateTime.now() : timestamp;
    }

    // 新增异常入参构造,配置专属Builder方法名
    @Builder(builderMethodName = "exceptionBuilder")
    public Foo(Exception exception, Integer status) {
        this.message = exception.getMessage();
        this.status = status;
        this.timestamp = LocalDateTime.now();
    }
}

说明:

  • 普通场景Builder调用:Foo.normalBuilder().message("操作失败").status(400).build()
  • 异常场景Builder调用:Foo.exceptionBuilder().exception(new RuntimeException("系统错误")).status(500).build()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 18:27:01