/**
*
* @author yw04009 Bill,wu
*
*/
public class Testa implements Serializable {
public int age;
Public Testb str = new StringBuffer ();
The public Object clone () throws Clonenotsupportedexception {//and The 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 are that Object ' t ' mush I Mplement 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 ();
}
}