private class CloneTest { private Long myLong = new Long(1); }
public static void main(String args[]) { new DeepCloneTest().Test(); }
public void Test() { CloneTest ct1 = new CloneTest(); CloneTest ct2 = ct1;
// to see if ct1 and ct2 are one same reference. System.out.println("ct1: " + ct1); System.out.println("ct2: " + ct2);
// if ct1 and ct2 point to one same object, then ct1.myLong == ct2.myLong. System.out.println("ct1.myLong: " + ct1.myLong); System.out.println("ct2.myLong: " + ct2.myLong);
// we change ct2's myLong ct2.myLong = 2L;
// to see whether ct1's myLong was changed. System.out.println("ct1.myLong: " + ct1.myLong); System.out.println("ct2.myLong: " + ct2.myLong); } }
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 DeepCloneTest {
// must implements Cloneable. private class CloneTest implements Serializable{ private static final long serialVersionUID = 1L; private Object o = new Object();
public CloneTest deepClone() { CloneTest ct = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(this); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois= new ObjectInputStream(bais); ct = (CloneTest)ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return ct; } }
public static void main(String args[]) { new DeepCloneTest().Test(); }
public void Test() { CloneTest ct1 = new CloneTest(); CloneTest ct2 = ct1.deepClone();
// to see if ct1 and ct2 are one same reference. System.out.println("ct1: " + ct1); System.out.println("ct2: " + ct2);