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
Why is Lombok @Builder not compatible with this constructor?
提问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 @Builder
Lombok annotation and everything was fine. But I added the constructor and the code does not compile any more. The error is:
首先,我只使用@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
So I have two questions:
所以我有两个问题:
- Why is Lombok
@Builder
not compatible with this constructor? - How do I make the code compile taking into account that I need both the builder and the constructor?
- 为什么 Lombok
@Builder
与此构造函数不兼容? - 考虑到我需要构建器和构造器,我该如何编译代码?
采纳答案by wdc
You can either add an @AllArgsConstructor
annotation, because
您可以添加@AllArgsConstructor
注释,因为
@Builder
generates 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 @Builder
is using. So you should just add annotation @AllArgsConstructor
to your class:
当您提供自己的构造函数时,Lombok 不会使用所有@Builder
正在使用的参数创建 c-tor 。所以你应该只@AllArgsConstructor
在你的类中添加注释:
@Data
@Builder
@AllArgsConstructor
public class RegistrationInfo {
//...
}
回答by Andrew Tobilko
Presumably, @Builder
generates 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);
}
}