Java DeepCopy via Serialization

Sometimes you need a way to make a deepcopy of all your objects. May be not the fastest :-). You have to ensure, that all of your objects are serializeable.

1
2
3
4
5
6
public static <T> T deepCopy(T o) throws Exception {  
ByteArrayOutputStream baos = new ByteArrayOutputStream();
new ObjectOutputStream(baos).writeObject(o);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
return (T) new ObjectInputStream(bais).readObject();
}