Last active
December 11, 2015 08:28
-
-
Save jarek-przygodzki/4573059 to your computer and use it in GitHub Desktop.
A Java deep clone (deep copy) using serialization
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
package utils; | |
import java.io.ByteArrayInputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.IOException; | |
import java.io.ObjectInputStream; | |
import java.io.ObjectOutputStream; | |
import java.io.Serializable; | |
public class CloneUtils { | |
/** | |
* This method makes a "deep clone" of any serializable object | |
*/ | |
public static <T extends Serializable> T deepClone(T object) | |
throws IOException, ClassNotFoundException { | |
ByteArrayOutputStream baos = new ByteArrayOutputStream(); | |
ObjectOutputStream oos = new ObjectOutputStream(baos); | |
oos.writeObject(object); | |
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); | |
ObjectInputStream ois = new ObjectInputStream(bais); | |
return (T) ois.readObject(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment