java 33 lines · 7 steps

Deep-copying objects via Jackson serialization

A utility that clones any object by serializing it to JSON bytes and reading it back into a fresh instance.

Explained by highlit
1public final class DeepCopier {
2 
3 private static final ObjectMapper MAPPER = new ObjectMapper()
4 .registerModule(new JavaTimeModule())
5 .findAndRegisterModules();
6 
7 private DeepCopier() {
8 }
9 
10 public static <T> T copy(T source, Class<T> type) {
11 if (source == null) {
12 return null;
13 }
14 try {
15 byte[] bytes = MAPPER.writeValueAsBytes(source);
16 return MAPPER.readValue(bytes, type);
17 } catch (IOException e) {
18 throw new IllegalStateException("Failed to deep-copy " + type.getSimpleName(), e);
19 }
20 }
21 
22 public static <T> T copy(T source, TypeReference<T> typeRef) {
23 if (source == null) {
24 return null;
25 }
26 try {
27 byte[] bytes = MAPPER.writeValueAsBytes(source);
28 return MAPPER.readValue(bytes, typeRef);
29 } catch (IOException e) {
30 throw new IllegalStateException("Failed to deep-copy value", e);
31 }
32 }
33}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Round-tripping through a serializer is a generic way to deep-copy without writing per-class clone logic.
  2. 2A shared, immutable ObjectMapper is thread-safe and worth reusing as a static singleton.
  3. 3TypeReference overloads let you preserve generic type information that a plain Class token would erase.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Deep-copying objects via Jackson serialization — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code