Java Object Deep Clone deepClone(final E object)

Here you can find the source of deepClone(final E object)

Description

deep Clone

License

Open Source License

Declaration

@SuppressWarnings("unchecked")
    public static <E extends Serializable> E deepClone(final E object) 

Method Source Code


//package com.java2s;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Main {
    @SuppressWarnings("unchecked")
    public static <E extends Serializable> E deepClone(final E object) {
        final E deepCopy = (E) doCopy(object);
        return deepCopy;
    }/*from   w  w  w  .  j  av a  2  s  . com*/

    private static Object doCopy(final Object object) {
        try {
            final Object copy;
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final ObjectOutputStream oos = new ObjectOutputStream(baos);
            final ByteArrayInputStream bais;
            final ObjectInputStream ois;
            oos.writeObject(object);
            bais = new ByteArrayInputStream(baos.toByteArray());
            ois = new ObjectInputStream(bais);
            copy = ois.readObject();
            return copy;
        } catch (final ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }

    }
}

Related

  1. deepClone(final T objectToBeClonned)
  2. deepClone(Object obj)
  3. deepClone(Object objToClone)
  4. deepClone(Object src)