【问题标题】:Why is Lombok @Builder not compatible with this constructor?为什么 Lombok @Builder 与此构造函数不兼容?
【发布时间】:2018-12-09 20:50:48
【问题描述】:

我有这个简单的代码:

@Data
@Builder
public class RegistrationInfo {

    private String mail;
    private String password;

    public RegistrationInfo(RegistrationInfo registrationInfo) {
        this.mail = registrationInfo.mail;
        this.password = registrationInfo.password;
    }
}

首先我只使用了@Builder Lombok 注释,一切都很好。但是我添加了构造函数,代码不再编译。错误是:

Error:(2, 1) java: constructor RegistrationInfo in class com.user.RegistrationInfo cannot be applied to given types;
  required: com.user.RegistrationInfo
  found: java.lang.String,java.lang.String
  reason: actual and formal argument lists differ in length  

所以我有两个问题:

  1. 为什么 Lombok @Builder 与此构造函数不兼容?
  2. 考虑到我需要构建器和构造器,如何编译代码?

【问题讨论】:

  • 从错误中,我假设 1) 构造函数中的参数数量不正确 2) 传递给构造函数的参数类型不正确
  • 所有构造函数或特定构造函数都会发生这种情况吗?即使更改构造函数的参数也会报错吗?
  • @wdc 我只有一个构造函数(代码中提到了)。我需要带有此参数的构造函数才能复制对象。
  • 你检查@Builder(toBuilder = true)了吗?这假设为您提供复制构造函数的功能。 Foo copy = original.toBuilder().build()
  • @wdc 刚刚尝试了您的解决方案。使用构造函数会更好。谢谢!

标签: java lombok


【解决方案1】:

您可以添加@AllArgsConstructor 注释,因为

@Builder 生成一个全参数的构造函数,如果没有其他的 构造函数定义。

(引用@Andrew Tobilko)

或者将属性设置为 @Builder : @Builder(toBuilder = true) 这为您提供了复制构造函数的功能。

@Builder(toBuilder = true)
class Foo {
    // fields, etc
}

Foo foo = getReferenceToFooInstance();
Foo copy = foo.toBuilder().build();

【讨论】:

  • 虽然是更简洁的方式和is backed up by the author,但它也违反直觉并且涉及创建不必要的实例(foo.toBuilder() 这里)
【解决方案2】:

当您提供自己的构造函数时,Lombok 不会创建具有 @Builder 正在使用的所有参数的 c-tor。所以你应该在你的类中添加注释@AllArgsConstructor

@Data
@Builder
@AllArgsConstructor
public class RegistrationInfo {
    //...
}

【讨论】:

    【解决方案3】:

    如果没有定义其他构造函数,@Builder 可能会生成一个全参数构造函数。

    @Data
    @Builder
    @AllArgsConstructor(access = AccessLevel.PRIVATE)
    class RegistrationInfo {
    
        private String mail;
        private String password;
    
        private RegistrationInfo(RegistrationInfo registrationInfo) {
            this(registrationInfo.mail, registrationInfo.password);
        }
    }
    

    【讨论】:

    • 在我的例子中,我使用默认构造函数,所以我不得不添加这个注解@NoArgsConstructor
    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 2013-03-03
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    相关资源
    最近更新 更多