01: package U2.T2.Obj;
02:
03: import java.io.*;
04:
05: //import U2.T2.examples.* ;
06:
07: /**
08: * Utility to do deep cloning of an object.
09: */
10: public class Cloner {
11:
12: // static public int BUFSIZE = 1000 ;
13:
14: /**
15: * Return a deep-clone of an object. Currently implemented via
16: * serialization; thus assuming that the cloned object is
17: * serializable.
18: */
19: static public <T> T clone(T o) throws IOException,
20: ClassNotFoundException {
21: ByteArrayOutputStream outstream = new ByteArrayOutputStream();
22: ObjectOutputStream cout = new ObjectOutputStream(outstream);
23: cout.writeObject(o);
24: ByteArrayInputStream instream = new ByteArrayInputStream(
25: outstream.toByteArray());
26: ObjectInputStream cin = new ObjectInputStream(instream);
27: T copy = (T) cin.readObject();
28: return copy;
29:
30: }
31:
32: // test:
33: /*
34: static public void main(String[] args) {
35: MyList xs = new MyList() ;
36: // xs.insert(1) ; xs.insert(-1) ;
37: xs = new MyList() ;
38: // circular :
39: xs.insert(0) ; xs.list.next = xs.list ;
40: System.out.println(Show.show(xs)) ;
41: MyList ys = null ;
42: try { ys = (MyList) clone(xs) ; }
43: catch (ClassNotFoundException e) { System.out.println("ouch 1") ; }
44: catch (IOException e) { System.out.println("ouch 2") ; } ;
45: ys.insert(0) ;
46: System.out.println(Show.show(ys)) ;
47: if (xs.getClass() == ys.getClass()) System.out.println("ok") ;
48: }
49: */
50: }
|