为什么 Lombok @Builder 与此构造函数不兼容?

Why is Lombok @Builder not compatible with this constructor?

我有这个简单的代码:

@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. 考虑到我同时需要生成器和构造函数,我该如何编译代码?

当您提供自己的构造函数时,Lombok 不会创建包含 @Builder 使用的所有参数的 c-tor。所以你应该只添加注释 @AllArgsConstructor 到你的 class:

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

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

@Data
@Builder
@AllArgsConstructor(access = AccessLevel.PRIVATE)
class RegistrationInfo {

    private String mail;
    private String password;

    private RegistrationInfo(RegistrationInfo registrationInfo) {
        this(registrationInfo.mail, registrationInfo.password);
    }
}

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

@Builder generates an all-args constructor iff there are no other constructors defined.

(引用 @Andrew Tobilko)

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

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

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