Deep Copy Tools

1. Copy the depth of tools

  Shallow copy (clone Object class () method) refers to a copy target at the time, of the basic variable data types will re-copy, and for the reference variable is just a reference to the type of copy.

        Deep copy (or clone called deep) is the subject content of the object and the associated objects will be a copy.

Package cn.xm.exam.utils; 

Import java.io.ByteArrayInputStream;
 Import java.io.ByteArrayOutputStream;
 Import java.io.ObjectInputStream;
 Import java.io.ObjectOutputStream; 

/ ** 
 * deep copy of tools 
 * 
 * @author Administrator 
 * 
 * / 
public  class CloneUtils { 
    @SuppressWarnings ( "an unchecked" )
     public  static <T> T cloneObj (T obj) { 
        T retVal = null ; 

        the try {
             // the objects written to the stream
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);

            // 从流中读出对象
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);

            retVal = (T) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return retVal;
    }
}

 

Guess you like

Origin www.cnblogs.com/qlqwjy/p/10951629.html