📅  最后修改于: 2023-12-03 15:02:47.955000             🧑  作者: Mango
Lombok is a popular Java library that provides annotations to automatically generate boilerplate code such as getters and setters, constructors, equals and hashcode methods, and more. One of the annotations that Lombok provides is @Getter
and @Setter
, which generates getters and setters for fields automatically.
However, in some cases, you may not want Lombok to generate getters and setters for some fields. For example, you may have a field that you want to keep private and not allow access to it from outside the class. In such cases, you can use the @Getter
and @Setter
annotations with the AccessLevel.NONE
argument to tell Lombok to not generate the getters and setters for that field.
Here's an example:
import lombok.Getter;
import lombok.Setter;
import lombok.AccessLevel;
public class MyClass {
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private String myPrivateField;
// rest of the class
}
In this example, we have a private field myPrivateField
and we want to prevent Lombok from generating getters and setters for it. We use the @Getter(AccessLevel.NONE)
and @Setter(AccessLevel.NONE)
annotations to achieve this.
When you use the @Getter
annotation with AccessLevel.NONE
, Lombok will not generate the getter method for the field. Similarly, when you use the @Setter
annotation with AccessLevel.NONE
, Lombok will not generate the setter method for the field.
By default, Lombok generates the getter and setter methods with the same access level as the field. But you can also specify a different access level by using the @Getter
and @Setter
annotations with the AccessLevel
argument. Here's an example:
import lombok.Getter;
import lombok.Setter;
import lombok.AccessLevel;
public class MyClass {
@Getter(AccessLevel.PROTECTED)
@Setter(AccessLevel.PACKAGE)
private String myField;
// rest of the class
}
In this example, we have a field myField
and we want to generate a protected getter method and a package-private setter method for it. We use the @Getter(AccessLevel.PROTECTED)
and @Setter(AccessLevel.PACKAGE)
annotations to achieve this.
In conclusion, the @Getter
and @Setter
annotations in Lombok are powerful tools that can help you generate boilerplate code automatically. By using the AccessLevel
argument, you can control the access level of the generated getter and setter methods. And by using AccessLevel.NONE
, you can tell Lombok to ignore certain fields and not generate getters and setters for them.