/**
*
* @author yw04009 Bill,Wu
*
*/
public class TestA implements Serializable {
public int age;
public TestB str = new StringBuffer();
public Object clone() throws CloneNotSupportedException { //and other simple clone methoe seems like return super.clone()
TestA cloned = (TestA)super.clone();
cloned.str = (TestB)this.str.clone(); //just give a demo for simple object 'str'
return cloned;
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
TestA te1 = new TestA();
te1.age = 11111;
TestA te2 = CloneTest.deepClone(te1);
System.out.println("Stream Deep Clone ======== " );
System.out.println("te1 hashcode : " + System.identityHashCode(te1));
System.out.println("te2 hashcode : " + System.identityHashCode(te2));
System.out.println("te1.age : " + te1.age);
System.out.println("te2.age : " + te2.age);
System.out.println("te1.str : " + te1.str);
System.out.println("te2.str : " + te2.str);
System.out.println("Shallow Clone ======== " );
TestA te3 = new TestA();
te3.age = 22222;
te3.str.append("gggggggggg");
TestA te4 = (TestA)te3.clone();
System.out.println("te3 hashcode : " + System.identityHashCode(te3));
System.out.println("te4 hashcode : " + System.identityHashCode(te4));
System.out.println("te3.age : " + te3.age);
System.out.println("te4.age : " + te4.age);
System.out.println("te3.str : " + te3.str);
System.out.println("te4.str : " + te4.str);
}
}
public class CloneTest {
@SuppressWarnings("unchecked")
public static <T> T deepClone(T t) throws Exception { //Stream Deep Clone : the weak point is that Object 't' mush implement Interface 'Serializable'
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(t);
// return (T) new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
return (T) new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray())).readObject();
}
}