/** SpagoBI, the Open Source Business Intelligence suite Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. **/ package it.eng.spagobi.studio.geo.util; import java.io.IOException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.ObjectInputStream; /** * Utility for making deep copies (vs. clone()'s shallow copies) of * objects. Objects are first serialized and then deserialized. Error * checking is fairly minimal in this implementation. If an object is * encountered that cannot be serialized (or that references an object * that cannot be serialized) an error is printed to System.err and * null is returned. Depending on your specific application, it might * make more sense to have copy(...) re-throw the exception. * * A later version of this class includes some minor optimizations. */ public class DeepCopy { /** * Returns a copy of the object, or null if the object cannot * be serialized. */ public static Object copy(Object orig) { Object obj = null; try { // Write the object out to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(bos); out.writeObject(orig); out.flush(); out.close(); // Make an input stream from the byte array and read // a copy of the object back in. ObjectInputStream in = new ObjectInputStream( new ByteArrayInputStream(bos.toByteArray())); obj = in.readObject(); } catch(IOException e) { e.printStackTrace(); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } return obj; } }