Last active
July 10, 2017 12:36
-
-
Save HussainDerry/f2b02bbc05de8ad9b53e000b38e07cab to your computer and use it in GitHub Desktop.
Helper method to deep clone serializable objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.io.*; | |
| /** | |
| * Contains helper method to deep clone serializable objects | |
| * @author Hussain Al-Derry <[email protected]> | |
| * @version 1.0 | |
| */ | |
| public class CloneUtils { | |
| /** | |
| * Deep clones an object using streams | |
| * | |
| * @param object The object to be cloned, must implement {@link Serializable} | |
| * @param clazz The object type | |
| * @return an exact clone of the given object | |
| * @throws IllegalStateException If an issue occurs while cloning the object | |
| */ | |
| public static <T> T deepClone(T object, Class<T> clazz){ | |
| try{ | |
| // Write provided object bytes to OutputStream | |
| ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream(); | |
| ObjectOutputStream mObjectOutputStream = new ObjectOutputStream(mByteArrayOutputStream); | |
| mObjectOutputStream.writeObject(object); | |
| // Reading bytes via a new InputStream | |
| ByteArrayInputStream mByteArrayInputStream = new ByteArrayInputStream(mByteArrayOutputStream.toByteArray()); | |
| ObjectInputStream ois = new ObjectInputStream(mByteArrayInputStream); | |
| // Creating the clone object | |
| return clazz.cast(ois.readObject()); | |
| }catch(IOException | ClassNotFoundException | ClassCastException e){ | |
| throw new IllegalStateException(e.getMessage(), e); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment