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:

JavaScript

Then code like this:

JavaScript

Prints out this:

JavaScript

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