Search code examples
setterlombok

How to add setter to Class using Lombok @Value


@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?


Solution

  • 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.)