问题
I have a class with a @Data annotation, but I'm not sure whether a constructor with arguments is generated or the only generated constructor is the default (no arguments) one from vanilla Java.
回答1:
A @RequiredArgsConstructor will be generated if no constructor has been defined.
The Project Lombok @Data page explains:
@Data is like having implicit @Getter, @Setter, @ToString, @EqualsAndHashCode and @RequiredArgsConstructor annotations on the class (except that no constructor will be generated if any explicitly written constructor exists).
回答2:
@Data is only creating a @RequiredArgsConstructor. Lombok documentation site for the Data annotation and constructors explains:
@RequiredArgsConstructor generates a constructor with 1 parameter for each field that requires special handling. All non-initialized final fields get a parameter, as well as any fields that are marked as @NonNull that aren't initialized where they are declared. For those fields marked with @NonNull, an explicit null check is also generated. The constructor will throw a NullPointerException if any of the parameters intended for the fields marked with @NonNull contain null. The order of the parameters match the order in which the fields appear in your class.
Suppose you have a POJO that uses Lombok @Data annotation:
public @Data class Z {
private String x;
private String y;
}
You can't create the object as Z z = new Z(x, y) because there is no arg on your Z class that is "required". It is creating the constructor with zero parameters because @Data gives you Setters and Getters for your properties and you can call setX and setY after creating your instance.
You can either make x and y @NonNull or final so they must be passed through the constructor or annotate your class Z with @AllArgsConstructor.
来源:https://stackoverflow.com/questions/41979374/does-the-project-lombok-data-annotation-create-a-constructor-of-any-kind