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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51122400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:58:01  来源:igfitidea点击:

Why is Lombok @Builder not compatible with this constructor?

javalombok

提问by IKo

I have this simple code:

我有这个简单的代码:

@Data
@Builder
public class RegistrationInfo {

    private String mail;
    private String password;

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

First I was using only the @BuilderLombok annotation and everything was fine. But I added the constructor and the code does not compile any more. The error is:

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

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  

So I have two questions:

所以我有两个问题:

  1. Why is Lombok @Buildernot compatible with this constructor?
  2. How do I make the code compile taking into account that I need both the builder and the constructor?
  1. 为什么 Lombok@Builder与此构造函数不兼容?
  2. 考虑到我需要构建器和构造器,我该如何编译代码?

采纳答案by wdc

You can either add an @AllArgsConstructorannotation, because

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

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

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

(Quotting @Andrew Tobilko)

(引用@Andrew Tobilko)

Or set an attribute to @Builder: @Builder(toBuilder = true)This gives you the functionality of a copy constructor.

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

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

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

回答by Cepr0

When you provide your own constructor then Lombok doesn't create a c-tor with all args that @Builderis using. So you should just add annotation @AllArgsConstructorto your class:

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

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

回答by Andrew Tobilko

Presumably, @Buildergenerates an all-args constructor iff there are no other constructors defined.

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

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

    private String mail;
    private String password;

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