Getter and Setter annotations

In this post under Lombok, I will show with example the purpose of Getter and Setter annotations.

These two annotations when used instructs Lombok to generate getter and setter methods.

We don’t need to use these two annotations always together. We can use the anyone of them based on our needs.

These two annotations can be applied at class level or at method level.

When applied at class level, lombok generates getter and setter methods for all the non-static fields in the class.

When applied to a specific non-static field, lombok generates getter and setter method for that particular field.

The methods generated by these annotations are by default public.

Below is the example of a class where these annotations are applied at class level


package package1;

import java.util.Date;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Person {
    private int id;
    private String firstName;
    private String middleName;
    private String lastName;
    private int age;
    private Date dateOfBirth;
}

Below is the example of a class where these annotations are applied at field level


package package1;

import lombok.Getter;
import lombok.Setter;

public class Rectangle {
    private int x;
    @Getter @Setter private int y;

    public Rectangle(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }
}

Below is the main class, that uses both these pojo class.

Main Class


1  package package1;
2  
3  import java.util.Date;
4  
5  public class Example1 {
6      public static void main(String[] args) {
7          Person person = new Person();
8          person.setId(1);
9          person.setFirstName("Ralph");
10         person.setMiddleName("S");
11         person.setLastName("Emmerson");
12         person.setAge(39);
13         person.setDateOfBirth(new Date());
14         
15         System.out.println(person.getId() + ":" + person.getFirstName() + ":" + person.getMiddleName() + ":" + person.getLastName() + ":" + person.getAge() + ":" + person.getDateOfBirth());
16         
17         Rectangle rectangle = new Rectangle(5, 10);
18         System.out.println(rectangle.getY());
19         
20         rectangle.setY(20);
21         System.out.println(rectangle.getY());
22     }
23 }

In the above main class as you see we can call all the getter and setter methods of “Person” class.

But we can only call “getY” and “setY” method on the “Rectangle” class as we don’t have “getX” and “setX” method in the “Rectangle” class.

In this way we can instruct lombok to generate getter and setter method for non-static fields of a class or for a particular non-static field in the class.

Leave a Reply