Sagar Gangwal
Sagar Gangwal

Reputation: 7937

Update specific field of Object using Builder in java

I have two class with me as mentioned below. I wanted to create two instances of class A.

I want to create instance obj2 from existing instance obj1 with updated value of a3 attribute as "Java".

I had tried below line using Builder, but it's not working.

A obj2 = obj1.builder().a3("Java").build();

I am able to do it with calling constructor, but I wanted to do it Builder pattern only.

@Builder
@Data
class A {
    String a1;
    String a2;
    String a3;
    B b;

    A(String b1, String b2, String b3, B b) {
        this.a1 = b1;
        this.a2 = b2;
        this.a3 = b3;
        this.b = b;
    }
}

@Builder
@Data
class B {
    String b1;
    String b2;
    String b3;

    B(String b1, String b2, String b3) {
        this.b1 = b1;
        this.b2 = b2;
        this.b3 = b3;
    }

}

class Main {
    public static void main(String[] args) {

        B b = new B("a", "b", "b");
        A obj1 = new A("a1", "b1", "b1", b);
        A obj2 = new A("x1", "y1", "z1", b);
List<A> list= new ArrayList<>();
list.add(obj1);
list.add(obj2);
list.forEach(a -> {a.toBuilder().a1("newA1").a2("newA2").build()});

        A obj3 = obj1.toBuilder().a3("Java").build();
    }
}

} }

As mentioned in updated code , i have list of A with me, and i want to update a1 and a2 attributes of all element in list using builder. But builder is not working fine with lambda. If i will use setter with below code it's working fine.

list.forEach(a -> {
a.setA1("newA1");
a.setA2("newA2");
});

I am not able to get updated values for a1 and a2 in case of Builder with Lambda

Upvotes: 1

Views: 8517

Answers (3)

akhtar
akhtar

Reputation: 11

There is no way you can update the fields in existing object using lombok Builder method. As few people suggested about toBuilder = true, it creates completely new object but doesn't update the existing object.

Only way is using @Setter annotation.

Upvotes: 0

the_tech_maddy
the_tech_maddy

Reputation: 597

Actually, you have to enable toBuilder() in the annotation. toBuilder() allows you to edit the current object.

@Builder(toBuilder = true)

and then doing obj1.toBuilder().a3("Java").build() should work.

Upvotes: 1

Andrew
Andrew

Reputation: 49606

obj1.builder() is an allowed but confusing way to say A.builder(). It's not recommended to call a static method on an instance. Either way, a completely new A will be created.

@Builder(toBuilder = true)

might be what you are looking for

If true, generate an instance method to obtain a builder that is initialized with the values of this instance. Legal only if @Builder is used on a constructor, on the type itself, or on a static method that returns an instance of the declaring type.

boolean toBuilder() default false;

Upvotes: 6

Related Questions