简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM