Java Object Deep Copy deepCopy(Object orig)

Here you can find the source of deepCopy(Object orig)

Description

NOTE: when updating the cloned object, the cloned associated collection in particular, Before persist using Hibernate, need to create a new collection using the cloned collection otherwise Hibernate complains.

License

BSD License

Declaration

public static Object deepCopy(Object orig) 

Method Source Code


//package com.java2s;
/*L//from   www .  ja  v a  2 s . c  o  m
 *  Copyright SAIC
 *  Copyright SAIC-Frederick
 *
 *  Distributed under the OSI-approved BSD 3-Clause License.
 *  See http://ncip.github.com/cananolab/LICENSE.txt for details.
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Main {
    /**
     * NOTE: when updating the cloned object, the cloned associated collection
     * in particular, Before persist using Hibernate, need to create a new
     * collection using the cloned collection otherwise Hibernate complains.
     */
    public static Object deepCopy(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;
    }
}

Related

  1. deepCopy(List src)
  2. deepCopy(List src)
  3. deepCopy(Object o)
  4. deepCopy(Object obj1, Object obj2)
  5. deepCopy(Object oldObj)
  6. deepCopy(Object original)
  7. deepCopy(Object toCopy)
  8. deepCopy(Serializable source)
  9. deepCopy(T item)