396

I want to use a data class in Lombok. Since it has about a dozen fields, I annotated it with @Data in order to generate all the setters and getter. However there is one special field for which I don't want to the accessors to be implemented.

How does Lombok omit this field?

2 Answers 2

692

You can pass an access level to the @Getter and @Setter annotations. This is useful to make getters or setters protected or private. It can also be used to override the default.

With @Data, you have public access to the accessors by default. You can now use the special access level NONE to completely omit the accessor, like this:

@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private int mySecret;
4
  • 1
    Perfect. If the private field is a POJO and also annotated with @Delegate(), it could be used for extracting a set of properties into a separate reusable class. This may be useful for having the same set of properties applied to multiple classes (kind of a mixin for adding properties). For example, a mixin representing a set of attributes that may apply to modeling of various XML elements.
    – xorcus
    Jan 30, 2018 at 13:08
  • 1
    Do you have similar thing to omitting one field in builder ?
    – zt1983811
    May 4, 2018 at 13:40
  • 2
    You mean the attribute should not show up in the builder? No, there is nothing directly for this. Remember though that @Builder can be put on functions and constructors as well as classes, and only offer setting those attributes that come up in the signature of that function. May 6, 2018 at 18:19
  • It doesn't implement any setter and getter for this property where @Data includes setters and getters by default. which would be excluded by mentioning AccessLevel.NONE.
    – Ram
    Feb 27, 2019 at 6:23
56

According to @Data description you can use:

All generated getters and setters will be public. To override the access level, annotate the field or class with an explicit @Setter and/or @Getter annotation. You can also use this annotation (by combining it with AccessLevel.NONE) to suppress generating a getter and/or setter altogether.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.