September 2019
Intermediate to advanced
816 pages
18h 47m
English
This technique requires serializable objects (implement java.io.Serializable). Basically, the object is serialized (writeObject()) and deserialized (readObject()) in a new object. A helper method able to accomplish this is listed as follows:
private static <T> T cloneThroughSerialization(T t) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(t); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); return (T) ois.readObject(); } catch (IOException | ClassNotFoundException ex) { // log exception return t; }}
So, the object is serialized in ObjectOutputStream ...