Java Lombok | Automatically Generating getter and setter Methods - @Getter @Setter

Using @Getter and @Setter

You can automatically generate getter methods with @Getter and setter methods with @Setter.

package com.devkuma.tutorial.lombok;

import lombok.Getter;
import lombok.Setter;

public class GetterSetterTutorial {

    @Getter
    @Setter
    private String value;

    public static void main(String[] args) {
        GetterSetterTutorial tutorial = new GetterSetterTutorial();

        tutorial.setValue("Hello @Getter, @Setter");
        System.out.println(tutorial.getValue());
    }

}

Execution result:

Hello @Getter, @Setter

Access Control with AccessLevel

You can also specify an access modifier.

package com.devkuma.tutorial.lombok;

import lombok.AccessLevel;
import lombok.Getter;

public class GetterAccessLevelTutorial {
    @Getter(AccessLevel.PRIVATE)
    private String value;
}
  • You can specify an access modifier by passing AccessLevel to value.

The code above is transformed as follows.

package com.devkuma.tutorial.lombok;

public class GetterAccessLevelTutorial {
    private String value;

    public GetterAccessLevelTutorial() {
    }

    private String getValue() {
        return this.value;
    }
}
  • You can see that the getter method for value, getValue(), is specified as private.

@Getter(lazy=true)

package com.devkuma.tutorial.lombok;

import lombok.Getter;

public class GetterLazyTutorial {
    public static void main(String[] args) {
        GetterLazyTutorial tutorial = new GetterLazyTutorial();
        System.out.println("Main instance is created");
        tutorial.getLazy();
    }

    @Getter
    private final String notLazy = createValue("not lazy");

    @Getter(lazy=true)
    private final String lazy = createValue("lazy");

    private String createValue(String name) {
        System.out.println("createValue(" + name + ")");
        return null;
    }
}

Execution result:

createValue(not lazy)
Main instance is created
createValue(lazy)

If you set lazy to true in @Getter, initialization of the value can be delayed until the getter method is called for the first time.