390

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?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
DerMike
  • 15,594
  • 13
  • 50
  • 63

2 Answers2

681

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;
Michael Piefel
  • 18,660
  • 9
  • 81
  • 112
  • 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 '18 at 13:08
  • 1
    Do you have similar thing to omitting one field in builder ? – zt1983811 May 04 '18 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. – Michael Piefel May 06 '18 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 '19 at 06:23
55

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197