code_junkie

How do you make a deep copy of an object in Java?

Nov 10th, 2011
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.89 KB | None | 0 0
  1. private static final XStream XSTREAM = new XStream();
  2. ...
  3.  
  4. Object newObject = XSTREAM.fromXML(XSTREAM.toXML(obj));
  5.  
  6. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  7. ObjectOutputStream oos = new ObjectOutputStream(bos);
  8. oos.writeObject(object);
  9. oos.flush();
  10. oos.close();
  11. bos.close();
  12. byte [] byteData = bos.toByteArray();
  13.  
  14. ByteArrayInputStream bais = new ByteArrayInputStream(byteData);
  15. (Object) object = (Object) new ObjectInputStream(bais).readObject();
  16.  
  17. if (instance1 == instance2) {
  18. // same instance
  19. }
  20. if (instance1.equals(instance2)) {
  21. // same value. maybe or maybe not same instance.
  22. }
  23.  
  24. import com.thoughtworks.xstream.XStream;
  25.  
  26. public class deepCopy {
  27.  
  28. private static XStream xstream = new XStream();
  29.  
  30.  
  31. //serialize with Xstream them deserialize ...
  32.  
  33. public static Object deepCopy(Object obj){
  34.  
  35.  
  36. return xstream.fromXML(xstream.toXML(obj));
  37.  
  38.  
  39. }
  40.  
  41.  
  42.  
  43. }
Add Comment
Please, Sign In to add comment