Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omitting one Setter/Getter in Lombok

Tags:

java

lombok

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?

like image 257
DerMike Avatar asked Nov 03 '11 11:11

DerMike


People also ask

How do you exclude a setter in Lombok?

Omitting Getter or Setter Using AccessLevel. To override the access level, annotate the field or class with an explicit @Setter or @Getter annotation.

Can I override a Lombok setter?

You can always manually disable getter/setter generation for any field by using the special AccessLevel. NONE access level. This lets you override the behaviour of a @Getter , @Setter or @Data annotation on a class.

Can we use getter without setter?

Depends on if the value you are talking about is something you want to let other classes modify - in some cases the answer is yes, in some it is no. If the answer is no then there is no reason to add a setter method and in fact it might harm things.


2 Answers

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; 
like image 112
Michael Piefel Avatar answered Sep 29 '22 11:09

Michael Piefel


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.

like image 43
Mark Rotteveel Avatar answered Sep 29 '22 12:09

Mark Rotteveel