Java Object Deep Clone deepClone(Object obj)

Here you can find the source of deepClone(Object obj)

Description

deep Clone

License

BSD License

Parameter

Parameter Description
obj must implement Serializable

Return

a deep copy of an object

Declaration

public static Object deepClone(Object obj) 

Method Source Code


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

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class Main {
    /**/*from w  ww  . j  a v  a2  s .  c  o  m*/
     *
     * @param obj
     *            must implement Serializable
     * @return a deep copy of an object
     */
    public static Object deepClone(Object obj) {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bin);
            return ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            close(oos);
            close(ois);
        }
    }

    public static void close(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Related

  1. deepClone(final E object)
  2. deepClone(final T objectToBeClonned)
  3. deepClone(Object objToClone)
  4. deepClone(Object src)
  5. deepClone(Object src)
  6. deepClone(Serializable o)