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 I add annotation @AllArgsConstructor
than I can't see 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 both constructor in Lombok
?
Your class is equivalent to:
@Accessors(chain = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Answer<T> {
private T data;
}
Although strictly speaking this adds toString
, equals
and hashCode
methods on all variables. This can (and often does) cause infinite loops. Be very wary of @Data
.
@Accessors(chain = true)
makes the setter
implementations return this
, more info here.
You can add multiple constructor annotations:
Unlike most other lombok annotations, the existence of an explicit constructor does not stop these annotations from generating their own constructor.
Note that @Accessors
is experimental so may be changed/renamed at some future point.
I prefer @Builder
to @AllArgsConstructor
as it allows only required parameters to be set, whereas a all arguments constructor is all or nothing. It also generates much more readable code, consider
new Thing(true, 1, 4, false, 4, 4.0)
Versus
new Thing.Builder().
setANamnedProperty(true).
setAnotherNamnedProperty(1).
....
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