Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add setter to Class using Lombok @Value

Tags:

setter

lombok

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

like image 846
LookIntoEast Avatar asked Oct 29 '25 10:10

LookIntoEast


2 Answers

I used @NonFinal and @Setter to achieve this without adjusting too much and staying in the lombok workflow.

I had a large model that I didn't want to refactor to have final variables on everything, so this was the simplest and cleanest solution for me.

@Value
@Builder
public class XXX {
    String field1;
    String field2;

    @NonFinal
    @Setter
    String field3;
}
like image 113
IsaacD Avatar answered Oct 31 '25 08:10

IsaacD


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

like image 26
Jan Rieke Avatar answered Oct 31 '25 08:10

Jan Rieke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!