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

3 Answers 3

7

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice solution, helped me to achieve exactly what I wanted. Just as remark: @NonFinal is still an experimental feature at the moment.
4

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

2 Comments

I tried this, but it seems Getter+Setter+AllArgsConstructor is not sufficient. It keeps bugging. Documentation said: "In practice, Value is shorthand for: final ToString EqualsAndHashCode AllArgsConstructor FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE) Getter". So maybe I should add all these annotations?
Solved by adding EqualsAndHashCode
-2

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

1 Comment

Because all fields will be made as final by @Value; so what changes to make for annotations so that we could specifically make field3 NOT final and have a setter for it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.