You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DeepCopy.java 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package com.vaadin.sass.util;
  2. import java.io.IOException;
  3. import java.io.ObjectInputStream;
  4. import java.io.ObjectOutputStream;
  5. /**
  6. * Utility for making deep copies (vs. clone()'s shallow copies) of objects.
  7. * Objects are first serialized and then deserialized. Error checking is fairly
  8. * minimal in this implementation. If an object is encountered that cannot be
  9. * serialized (or that references an object that cannot be serialized) an error
  10. * is printed to System.err and null is returned. Depending on your specific
  11. * application, it might make more sense to have copy(...) re-throw the
  12. * exception.
  13. */
  14. public class DeepCopy {
  15. /**
  16. * Returns a copy of the object, or null if the object cannot be serialized.
  17. */
  18. public static Object copy(Object orig) {
  19. Object obj = null;
  20. try {
  21. // Write the object out to a byte array
  22. FastByteArrayOutputStream fbos = new FastByteArrayOutputStream();
  23. ObjectOutputStream out = new ObjectOutputStream(fbos);
  24. out.writeObject(orig);
  25. out.flush();
  26. out.close();
  27. // Retrieve an input stream from the byte array and read
  28. // a copy of the object back in.
  29. ObjectInputStream in = new ObjectInputStream(fbos.getInputStream());
  30. obj = in.readObject();
  31. in.close();
  32. } catch (IOException e) {
  33. e.printStackTrace();
  34. } catch (ClassNotFoundException cnfe) {
  35. cnfe.printStackTrace();
  36. }
  37. return obj;
  38. }
  39. }