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:
@Builder
not compatible with this constructor? When we annotate a class with @Builder, Lombok creates a builder for all instance fields in that class. We've put the @Builder annotation on the class without any customization. Lombok creates an inner static builder class named as StudentBuilder. This builder class handles the initialization of all fields in Student.
Lombok's @Builder annotation is a useful technique to implement the builder pattern that aims to reduce the boilerplate code. In this tutorial, we will learn to apply @Builder to a class and other useful features. Ensure you have included Lombok in the project and installed Lombok support in the IDE.
Martin Grajcar. Your @Builder needs an @AllArgsConstructor (add it; feel free to make it private).
The @SuperBuilder annotation produces complex builder APIs for your classes. In contrast to @Builder , @SuperBuilder also works with fields from superclasses. However, it only works for types. Most importantly, it requires that all superclasses also have the @SuperBuilder annotation.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With