Annotation for various constructors 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();
Have you tried this?
@NoArgsConstructor
@AllArgsConstructor
Yes, you can use both constructor in Lombok.
@NoArgsConstructor
@AllArgsConstructor
@AllArgsConstructor generates a constructor requiring an argument for every field in the annotated class.
So we have the Employee class with two fields:
@AllArgsConstructor
public class Employee {
private String name;
private int salary;
}
When we de-lombok the class, it becomes:
public class Employee {
private String name;
private int salary;
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
@NoArgsConstructor generates a default constructor with no parameters.
We have the following Employee class:
@NoArgsConstructor
public class Employee {
private String name;
private int salary;
}
When we look at the generated code, we see that Lombok adds a no-args constructor:
public class Employee {
private String name;
private int salary;
public Employee() {
}
}
More examples