Skip to content
Advertisement

Can @Builder be used for object creation as well as object modification?

I recently learned about object creation using @builder. But suddenly, I wonder if @Builder can be used to modify an object that has already been created.

When I try to modify an object using @setter, the advantage of creating a constructor with @builder seems to disappear. So I tried to modify only some variables using @builder, but it seems to create a new object altogether.

Is there a way to modify an object using @Builder?
Or should I just use a setter or create a separate function when modifying an object?

Advertisement

Answer

Not exactly modify, but you can use it as sort of copy constructor, which creates a new object builder out of old one. Then you can modify only the specific fields. Annotate your object with @Builder(toBuilder=true) and then call .toBuilder() on the object instance.

Very handy when dealing with immutable objects.

Example:

@Value
@Builder(toBuilder = true)
public class A {
    String name;
    long value;
}

Then code like this:

var a = A.builder().name("test-name").value(1234L).build();
System.out.println(a);
var b = a.toBuilder().value(4321L).build();
System.out.println(b);

Prints out this:

A(name=test-name, value=1234)
A(name=test-name, value=4321)

References:

https://projectlombok.org/features/Builder

https://projectlombok.org/features/Value

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement