How to use @Accessors in Java Lombok?
In Java Lombok, the @Accessors annotation is used to configure the access level and naming style of the generated getter and setter methods.
@Accessors can be configured with the following properties:
- linked series of metal rings or loops
- fluent – able to speak or write easily and smoothly in a particular language or skill
- starting part
- idle
@Accessors can be configured at both the class level and property level. When configured at the class level, the same access level and naming convention will be applied to all properties in that class. At the property level, different configurations can be specified for each property individually.
Here is an example:
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
@Getter
@Setter
@ToString
@Accessors(chain = true, fluent = true, prefix = "my", lazy = true)
public class Example {
private String name;
private int age;
}
public class Main {
public static void main(String[] args) {
Example example = new Example().myName("Alice").myAge(20);
System.out.println(example);
}
}
In the example above, we used the @Accessors annotation at the class level to configure features such as chained calls, removing prefixes, and lazy initialization. As a result, we can set attribute values through chained calls and the generated getter and setter methods do not have the get and set prefixes. In the Main class, we created an Example object and used the generated setter methods to set the attribute values. Finally, when printing the Example object, the generated toString method is called to output the object’s values.