How to add setter to Class using Lombok @Value

Viewed 3173
@Value
@Builder
public class XXX {
    String field1;
    String field2;
    String field3;
}

I have a class using lombok @Value as above, where each field will be made private and final. Now, I'd like to have a setter for field3, which does not work because field3 is final. What should I do here?

2 Answers

Don't use @Value then. @Value is for value classes, i.e., classes whose instances are immutable. If you want a field to be mutable, then you clearly don't have a value class.

Instead, make all other fields final manually. Then use @Getter and @RequiredArgsConstructor (and @EqualsAndHashCode if required) on the class, and @Setter on all non-final fields. (Or use @Data, but carefully read its documentation.)

Why is the field3 final? When a variable is declared with final keyword, its value can’t be modified, essentially, a constant. You should remove it!

Here you set the properties when you create the object

XXX s= XXX.builder().field1("XX").field2("XX").field3("XX").build(); setter are not needed here

Related