Java Object Deep Copy deepCopy(Object o)

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

Description

deep Copy

License

Open Source License

Declaration

public static Object deepCopy(Object o) throws IOException, ClassNotFoundException 

Method Source Code


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

public class Main {
    public static Object deepCopy(Object o) throws IOException, ClassNotFoundException {
        byte[] bytes = serializeToByteArray(o);
        return deserializeFromByteArray(bytes);
    }//from ww  w  . j  a v  a 2 s .c om

    public static byte[] serializeToByteArray(Object obj) throws NotSerializableException {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(baos);
            out.writeObject(obj);
            return baos.toByteArray();
        } catch (NotSerializableException e) {
            e.fillInStackTrace();
            throw e;
        } catch (IOException e) {

            throw new Error("IOException writing to a byte array!");
        }
    }

    public static Object deserializeFromByteArray(byte[] bytes) throws IOException, ClassNotFoundException {
        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
        return in.readObject();
    }

    public static byte[] toByteArray(Object obj) throws NotSerializableException {
        return serializeToByteArray(obj);
    }
}

Related

  1. deepCopy(File fromDir, File toDir)
  2. deepCopy(final Class c, final Serializable s)
  3. deepCopy(final Object oldObj)
  4. deepCopy(List src)
  5. deepCopy(List src)
  6. deepCopy(Object obj1, Object obj2)
  7. deepCopy(Object oldObj)
  8. deepCopy(Object orig)
  9. deepCopy(Object original)