Getter and Setter annotations with AccessLevel

In previous post under Lombok, I showed how to inform Lombok to generate getter and setter methods automatically.

By default getter and setter methods generated by Lombok have public access modifier.

We can change the access modifier by taking help of “AccessLevel” attribute as shown below.

1  package package2;
3  import lombok.AccessLevel;
4  import lombok.Getter;
5  import lombok.Setter;
7  @Getter
8  @Setter
9  public class Rectangle {
10     private int x;
12     @Getter(AccessLevel.PRIVATE)
13     private int y;
15     public Rectangle(int x, int y) {
16         super();
17         this.x = x;
18         this.y = y;
19     }
20 }

In the above pojo class at line 7 and 8, we are instructing Lombok to generate getter and setter for all the fields in the “Rectangle” class.

At line 12, we are overriding this default behavior by providing AccessLevel.PRIVATE attribute. This will generate a private getter method for field “y”.

As a result, Lombok will generate getter and setter with public access modifier for field “x” but for field “y”, it will generate public setter method and private getter method.

Leave a Reply