Build an object from an existing one using lombok
To clone an object and modify properties using Lombok, annotate your class with @Builder(toBuilder = true), enabling the toBuilder() method:
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:
Meet toBuilder alternatives
Lombok is like the know-it-all friend, but not for everything. Enter Jackson's ObjectMapper for the cloning business:
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:
toBuilderfor multiple changes,@Withfor 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.
Was this article helpful?