'Why is Lombok @Builder not compatible with this constructor?
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:
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?
Solution 1:[1]
You can either add an @AllArgsConstructor
annotation, because
@Builder
generates an all-args constructor iff there are no other constructors defined.
(Quotting @Andrew Tobilko)
Or set an attribute to @Builder
: @Builder(toBuilder = true)
This give you the functionality of a copy constructor.
@Builder(toBuilder = true)
class Foo {
// fields, etc
}
Foo foo = getReferenceToFooInstance();
Foo copy = foo.toBuilder().build();
Solution 2:[2]
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:
@Data
@Builder
@AllArgsConstructor
public class RegistrationInfo {
//...
}
Solution 3:[3]
Presumably, @Builder
generates an all-args constructor if there are no other constructors defined.
@Data
@Builder
@AllArgsConstructor(access = AccessLevel.PRIVATE)
class RegistrationInfo {
private String mail;
private String password;
private RegistrationInfo(RegistrationInfo registrationInfo) {
this(registrationInfo.mail, registrationInfo.password);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Cepr0 |
Solution 3 | rjdkolb |