Annotations for different designers in Lombok?

I have a class

public class Answer<T> { private T data; public Answer(T data) { this.data = data; } public Answer() { } public T getData() { return data; } public Answer<T> setData(T data) { this.data = data; return this; } } 

which I want to simplify with Lombok .

If you add the annotation @AllArgsConstructor , then I can not see the default constructor.

 @Data @AllArgsConstructor public class Answer<T> { private T data; public Answer<T> setData(T data) { this.data = data; return this; } } 

Is it possible to have as a constructor in Lombok ?

+14
source share
3 answers

Your class is equivalent to:

 @Accessors(chain = true) @Data @NoArgsConstructor @AllArgsConstructor public class Answer<T> { private T data; } 

Although, strictly speaking, this adds the toString , equals and hashCode methods to all variables. This can (and often) causes endless loops. Be very careful with @Data .

@Accessors(chain = true) does implementations of setter return this , in more detail here .

You can add some constructor annotations:

Unlike most other lombok annotations, the existence of an explicit constructor does not stop these annotations from creating your own constructor.

Please note that @Accessors is experimental, so you can change / rename it at some future point.

I prefer @Builder to @AllArgsConstructor , since it allows you to set only the required parameters, while all argument constructors are all or nothing, It also generates much more readable code, consider

 new Thing(true, 1, 4, false, 4, 4.0) 

Vs

 new Thing.Builder(). setANamnedProperty(true). setAnotherNamnedProperty(1). .... build(); 
+25
source

Have you tried this?

 @NoArgsConstructor @AllArgsConstructor 
+11
source

Try it. That should work. Also add this annotation.

@NoArgsConstructor

@NoArgsConstructor will generate a constructor without parameters. If this is not possible (due to the last fields), a compiler error will occur instead, unless @NoArgsConstructor (force = true) is used, then all trailing fields are initialized with 0 / false / null. For fields with constraints, such as @NonNull fields, a check is not generated, so keep in mind that these constraints will usually not be executed until these fields are properly initialized later. Some Java constructs, such as hibernate and the Service Provider interface, require a constructor with no arguments. This annotation is useful primarily in combination with @Data or one of the other annotation generating constructors.

0
source

Source: https://habr.com/ru/post/975194/


All Articles