Java Object Deep Copy deeplyCopy(Serializable serializable)

Here you can find the source of deeplyCopy(Serializable serializable)

Description

deeply Copy

License

Apache License

Declaration

public static Serializable deeplyCopy(Serializable serializable) 

Method Source Code


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

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 {

    public static Serializable deeplyCopy(Serializable serializable) {

        try {/*from w  w w  . ja  v a 2s  .  c  o m*/
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(serializable);
            objectOutputStream.close();
            byteArrayOutputStream.close();

            byte[] bytes = byteArrayOutputStream.toByteArray();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            Serializable copy = (Serializable) objectInputStream.readObject();
            objectInputStream.close();
            byteArrayInputStream.close();

            return copy;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. deepCopy(Serializable source)
  2. deepCopy(T item)
  3. deepCopy(T originalObject)
  4. deepCopy(T src)
  5. deepCopy(T t)