Using @Data annotation example

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


package package21;

import lombok.Data;
import lombok.NonNull;

public class Person {
    private String firstName;
    private String middleName;
    private String lastName;
    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.

Leave a Reply