/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * A simple class for copying an object without using the clone method
 * @author Nathan Stevens
 * @created Nov 14, 2008;
 * @version 0.1 11/14/2008
 */
import java.io.*;

public class ObjectCopyUtil {
  // so that nobody can accidentally create an ObjectCopyUtil object
  private ObjectCopyUtil() {
  }

  // returns a deep copy of an object
  static public Object deepCopy(Object oldObj) throws Exception {
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    try {
      ByteArrayOutputStream bos =
              new ByteArrayOutputStream(); // A
      oos = new ObjectOutputStream(bos); // B
      // serialize and pass the object
      oos.writeObject(oldObj);   // C
      oos.flush();               // D
      ByteArrayInputStream bin =
              new ByteArrayInputStream(bos.toByteArray()); // E
      ois = new ObjectInputStream(bin);                  // F
      // return the new object
      return ois.readObject(); // G
    } catch (Exception e) {
      System.out.println("Exception in ObjectCloner = " + e);
      throw (e);
    } finally {
      oos.close();
      ois.close();
    }
  }

}
