In this post under Lombok, I will explain with example the purpose and how to use “@Data” annotation.
In all my previous posts under Lombok,
1) if I need to add getter, setter I would add “@Getter” and “@Setter” annotation
2) if I need to add toString method, I would add “@ToString” annotation
3) if I need to add equals and hashCode method, I would add “@EqualsAndHashCode”
4) if I need to add constructor to initialize all fields of a class, I would add “@RequiredArgConstructor”
Too many annotations to clutter the POJO class.
We can avoid this by replacing all these annotations with just one annotation and that is called “@Data” annotation.
“@Data” annotation is an alternative for “@Getter”, “@Setter”, “@ToString”, “@EqualsAndHashCode”, and “@RequiredArgConstructor”.
Below is the Person class that shows how to use “@Data” annotation
Person
package package21;
import lombok.Data;
import lombok.NonNull;
@Data
public class Person {
@NonNull
private String firstName;
@NonNull
private String middleName;
@NonNull
private String lastName;
@NonNull
private float salary;
}
This creates a “Person” class with getter and setter for each fields, toString method, equals method, hashCode method, and a constructor with parameters for all the fields as all of them are required.
The attributes like “callSuper”, “doNotUseGetters”, etc that I covered earlier will have default values.
If you want to set these attributes, we need to use specific annotations instead of “@Data” annotation.
In this way we can use “@Data” annotation.