Explain Codes LogoExplain Codes Logo

Build an object from an existing one using lombok

java
best-practices
object-oriented-programming
lombok
Alex KataevbyAlex Kataev·Sep 27, 2024
TLDR

To clone an object and modify properties using Lombok, annotate your class with @Builder(toBuilder = true), enabling the toBuilder() method:

@Builder(toBuilder = true) public class Example { private String data; // Assume other fields } Example original = new Example("original"); Example clone = original.toBuilder().build();

Important points:

  • Activate @Builder(toBuilder = true) for the class
  • Use original.toBuilder() for object cloning
  • Apply .build() for the final touch

When to whip out toBuilder

Put toBuilder to use when immutability comes into play or a new pricey instance needs to be fired up, just to slightly modify properties. It's a recipe for sanity versus manually rehashing every property.

The efficient @With for quick changes

Change the narrative with one or two fields using @With, which gifts your class with with methods for a field. This lets you create a fresh instance without the burden of a builder:

@Data @With public class Example { private final String data; private final int count; // And so we begin... } Example example = new Example("data", 42); Example modified = example.withData("newData"); // Voila! New data with @With

Meet toBuilder alternatives

Lombok is like the know-it-all friend, but not for everything. Enter Jackson's ObjectMapper for the cloning business:

ObjectMapper mapper = new ObjectMapper(); Example source = new Example("source"); Example cloned = mapper.convertValue(source, Example.class); // Cloned? More like twinned!

But remember: your ObjectMapper, like a fussy eater, needs the right configurations—ignoring null, handling specific property conversions—to enjoy the meal.

Let's talk performance

Looking for a fling? @With saves the overhead of builder love, making it apt for single property changes. But if you're crazy about modifying properties, just stick to toBuilder() here.

Juggling complex objects

As you venture into complex object jungles, deep copying becomes your trusty machete. toBuilder is like a pocket knife at best for nested copying, so consider sprinkling some deep copy magic on toBuilder() for perfect replication.

Handling inheritance with @SuperBuilder

Meet @SuperBuilder, the big brother of toBuilder, when your classes have family ties. Cloning objects with inheritance isn't mere child's play, but @SuperBuilder offers type safety with the swagger of the builder pattern.

Cloning cheat sheet

  • Play your cards right: toBuilder for multiple changes, @With for singles.
  • Steer clear of unnecessary objects to lower memory usage (your GC will thank you!)
  • Immutable objects offer built-in cloning through their constructors.
  • Remember: encapsulate your object for mutation protection.