DeepCopy.java

Download DeepCopy.java

 1: // Found at <http://javatechniques.com/blog/faster-deep-copies-of-java-objects/>.
 2: // Read on 10/19/2010.  Author: Philip Isenhour
 3: //
 4: // Adapted (and modified) on 10/2010 by Wayne Pollock, Tampa Florida USA
 5: 
 6: import java.io.*;
 7: import java.util.*;
 8: 
 9: /**
10:  * Utility for making deep copies (vs. clone()'s shallow copies) of
11:  * objects. Objects are first serialized and then deserialized. Error
12:  * checking is fairly minimal in this implementation. If an object is
13:  * encountered that cannot be serialized (or that references an object
14:  * that cannot be serialized) an error is printed to System.err and
15:  * null is returned. Depending on your specific application, it might
16:  * make more sense to re-throw the (caught) exception.
17:  */
18: 
19: public class DeepCopy {
20: 
21:     /**
22:      * Returns a copy of the object, or null if the object cannot
23:      * be serialized.
24:      */
25:     public static Object copy ( Object orig ) {
26:         Object obj = null;
27:         try {
28:             // Write the object out to a byte array:
29:             ByteArrayOutputStream bos = new ByteArrayOutputStream();
30:             ObjectOutputStream out = new ObjectOutputStream(bos);
31:             out.writeObject(orig);
32:             out.flush();
33:             out.close();
34: 
35:             // Make an input stream from the byte array and read
36:             // a copy of the object back in:
37:             ObjectInputStream in = new ObjectInputStream(
38:                 new ByteArrayInputStream(bos.toByteArray()));
39:             obj = in.readObject();
40:         }
41:         catch(IOException e) {
42:             e.printStackTrace();
43:         }
44:         catch(ClassNotFoundException cnfe) {
45:             cnfe.printStackTrace();
46:         }
47:         return obj;
48:     }
49: 
50: }
51: 
52: // Test class: makes an array of Date objects, tries to deepCopy it:
53: 
54: class DeepCopyDemo {
55:    @SuppressWarnings("deprecation")  // For Date.setYear
56:    public static void main ( String [] args ) {
57:       Date [] dates = new Date[]{ new Date(), new Date() };
58:       Date [] dateCopy = (Date[]) DeepCopy.copy( dates );
59: 
60:       // Now we change one of the date object in the original:
61:       dates[1].setYear(101);  // Sets the year to 2001
62: 
63:       // Now see if the copy has the old or changed date:
64:       System.out.println( "Original Date array: " + Arrays.toString( dates ) );
65:       System.out.println( "Date array copy:     " + Arrays.toString( dateCopy ) );
66: 
67:       if ( dates[1].getYear() != dateCopy[1].getYear() )
68:          System.out.println( "\nDeep copy successful!" );
69:       else
70:          System.out.println( "\nDeep copy failled (shallow copy was created)!" );
71:    }
72: }