Java Object Deep Copy deepCopy(Object toCopy)

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

Description

Creates a deep copy of an object using serialization.

License

Apache License

Declaration

public static Object deepCopy(Object toCopy) 

Method Source Code

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

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

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

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

public class Main {
    /**//from  w ww.jav a 2  s .c o  m
     * Creates a deep copy of an object using serialization.
     */
    public static Object deepCopy(Object toCopy) {
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        byte[] storedObjectArray;
        {
            try (ObjectOutputStream p = new ObjectOutputStream(
                    new BufferedOutputStream(ostream))) {
                p.writeObject(toCopy);
                p.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            storedObjectArray = ostream.toByteArray();
        }

        Object toReturn = null;
        try (ByteArrayInputStream istream = new ByteArrayInputStream(
                storedObjectArray)) {
            ObjectInputStream p;
            p = new ObjectInputStream(new BufferedInputStream(istream));
            toReturn = p.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return toReturn;
    }
}

Related

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