Java Object Deep Copy deepCopy(final Object oldObj)

Here you can find the source of deepCopy(final Object oldObj)

Description

deep Copy

License

Open Source License

Declaration

static public Object deepCopy(final Object oldObj) 

Method Source Code


//package com.java2s;
/*//from  ww  w. j  ava 2s  .co  m
 * Copyright (C) 2011 Openismus GmbH
 *
 * This file is part of GWT-Glom.
 *
 * GWT-Glom is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * GWT-Glom is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with GWT-Glom.  If not, see <http://www.gnu.org/licenses/>.
 */

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

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

public class Main {
    static public Object deepCopy(final Object oldObj) {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;

        try {
            final ByteArrayOutputStream bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            // serialize and pass the object
            oos.writeObject(oldObj);
            oos.flush();
            final ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bin);

            // return the new object
            return ois.readObject();
        } catch (final Exception e) {
            System.out.println("Exception in deepCopy:" + e);
            return null;
        } finally {
            try {
                oos.close();
                ois.close();
            } catch (final IOException e) {
                System.out.println("Exception in deepCopy during finally: " + e);
                return null;
            }
        }
    }
}

Related

  1. deepCopy(File fromDir, File toDir)
  2. deepCopy(final Class c, final Serializable s)
  3. deepCopy(List src)
  4. deepCopy(List src)
  5. deepCopy(Object o)
  6. deepCopy(Object obj1, Object obj2)