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.

- 4,040
- 6
- 27
- 44
2 Answers
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).

- 4,040
- 6
- 27
- 44
-
2How Lombok decides which of (possible) multiple instances to use for constructor argument? when used Data or RequiredArgsConstructor annotations – Ewoks Sep 26 '19 at 12:55
@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.

- 15,323
- 3
- 31
- 44

- 151
- 1
- 3