Search code examples
javalombokbuilder

How to update any parameter value of existing java lombok Builder object?


If I have a @Builder AnObj,

import lombok.Builder;

@Builder public class AnObj {

    private final String name;
    private final int age; 
}

with its properties (name, age), and there is an instance created

        AnObj a = AnObj.builder()
                .name("abc")
                .age(25)
                .build();
        System.out.println("anInstance: " + a.toBuilder().toString());
// Prints 
 anInstance: AnObj.AnObjBuilder(name=abc, age=25)

then how can I use the same object(a) but with an updated value in one of the parameter(say, age to be 40)

I tried,

    a.toBuilder().age(40).build();
    System.out.println("anInstance after update: " + a.toBuilder().toString());

// Prints the same values again:
 anInstance after update: AnObj.AnObjBuilder(name=abc, age=25)  

Expected result to be printed:

*// AnObj.AnObjBuilder(name=abc, age=40)*

Thanking in advance for your time.


Solution

  • When you call toBuilder.age(40).build() you are not reassigning that to the instance. The code should look like this:

    a = a.toBuilder().age(40).build();
    

    Let me know if it has been helpful.