Java : Creating a deep copy of an object

This page last changed on Jul 17, 2006 by Kees de Kooter

/**
 * Utility class for making deep copies of an object. It uses serialization to
 * do the trick. The developer has to make sure that either all members are
 * serializable.
 * 
 * @author Kees de Kooter (kees@boplicity.net)
 * @date 17-jul-2006
 * 
 * @see http://www.javaworld.com/javaworld/javatips/jw-javatip76.html
 */
public class ObjectCopier {

    private static Logger logger = LoggerFactory.getLogger(ObjectCopier.class);

    public static Object deepCopy(Object oldObj) {
        
        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream objectInputStream = null;
        Object result = null;
        
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            
            // serialize and pass the object
            objectOutputStream.writeObject(oldObj);
            objectOutputStream.flush();
            
            ByteArrayInputStream byteArrayInputStream = 
                new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            
            // return the new object
            result = objectInputStream.readObject();
        } catch (Exception e) {
            logger.error(e.toString());
        } finally {
            try {
                objectOutputStream.close();
                objectInputStream.close();
            } catch (IOException e) {
                logger.error(e.toString());
            }
        }
        
        return result;
    }
}