Skip to content

Instantly share code, notes, and snippets.

@Audhil
Created May 5, 2017 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Audhil/f4b8ff8c16a1876fcee3ac24b53d1848 to your computer and use it in GitHub Desktop.
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/
// 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