Skip to content

Instantly share code, notes, and snippets.

@krystalmonolith
Last active November 29, 2018 13:04
Show Gist options
  • Save krystalmonolith/d509248cc1b10db590b537e0b971b8d4 to your computer and use it in GitHub Desktop.
Save krystalmonolith/d509248cc1b10db590b537e0b971b8d4 to your computer and use it in GitHub Desktop.
Generic Java Deep Copy Class
package com.example;
import java.io.*;
public class DeepCopy {
private Class<?> clazz;
private byte[] byteData;
public <T> DeepCopy(T t) {
saveObject(t);
}
public <T> T copy() {
return loadObject();
}
private <T> void saveObject(T t) {
clazz = t.getClass();
try {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(t);
oos.flush();
byteData = bos.toByteArray();
}
}
} catch (IOException e) {
throw new IllegalStateException("Error serializing class " + clazz.getName(), e);
}
}
private <T> T loadObject() {
if (byteData != null && clazz != null) {
try (ByteArrayInputStream bais = new ByteArrayInputStream(byteData)) {
T rv = (T) new ObjectInputStream(bais).readObject();
return rv;
} catch (IOException e) {
throw new IllegalStateException("Error de-serializing " + clazz.getName(), e);
} catch (ClassNotFoundException ce) {
throw new IllegalStateException("Error de-serializing " + clazz.getName(), ce);
}
} else {
throw new IllegalArgumentException("Error de-serializing, byteData not initialized!");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment