Pages

Deep copy object

import java.io.*;

public class Clone {
/**
* Returns a deep of the object, or null if the object cannot
* be serialized.
*/
public static Object deep(final Object orig) {
Object obj = null;

try {

// Write the object out to a byte array
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final ObjectOutputStream out = new ObjectOutputStream(bos);

out.writeObject(orig);
out.flush();
out.close();

// Make an input stream from the byte array and read
// a deep of the object back in.
final ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bos.toByteArray()));

obj = in.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}

return obj;
}
}

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.