Java Object Deep Copy deepCopy(Serializable source)

Here you can find the source of deepCopy(Serializable source)

Description

Utility for making deep copies (vs.

License

Apache License

Declaration

public static Serializable deepCopy(Serializable source) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Main {
    /**/* w  w  w . j  a  va  2 s  . c  o  m*/
     * Utility for making deep copies (vs. clone()'s shallow copies) of
      * objects. Objects are first serialized and then deserialized.
      * 
      * Uses standard (slow) serialization
      */
    public static Serializable deepCopy(Serializable source) {
        Object copy = null;

        try {
            // Write the object out to a byte array
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bos);
            out.writeObject(source);
            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()));
            copy = in.readObject();
        } catch (Exception e) {
            throw new RuntimeException("error at deepCopy()", e);
        }
        return (Serializable) copy;
    }
}

Related

  1. deepCopy(Object obj1, Object obj2)
  2. deepCopy(Object oldObj)
  3. deepCopy(Object orig)
  4. deepCopy(Object original)
  5. deepCopy(Object toCopy)
  6. deepCopy(T item)
  7. deepCopy(T originalObject)
  8. deepCopy(T src)
  9. deepCopy(T t)