Created
May 5, 2017 14:00
-
-
Save Audhil/f4b8ff8c16a1876fcee3ac24b53d1848 to your computer and use it in GitHub Desktop.
Tip to copy a Java Object. for more info visit http://javatechniques.com/blog/faster-deep-copies-of-java-objects/
This file contains 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
// copying | |
public static Object copy(Object orig) { | |
Object obj = null; | |
try { | |
// Write the object out to a byte array | |
ByteArrayOutputStream bos = new ByteArrayOutputStream(); | |
ObjectOutputStream out = new ObjectOutputStream(bos); | |
out.writeObject(orig); | |
out.flush(); | |
out.close(); | |
// Make an input stream from the byte array and read | |
// a copy of the object back in. | |
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray())); | |
obj = in.readObject(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} catch (ClassNotFoundException cnfe) { | |
cnfe.printStackTrace(); | |
} | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment