Java Clone Class

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

public class Clone {
    public static Object clone(Object source) {
        Object newObject = new Object();
        ObjectOutputStream ooStr = null;

        try {
            ByteArrayOutputStream baoStr = new ByteArrayOutputStream();
            ooStr = new ObjectOutputStream(baoStr);
            ooStr.writeObject(source);
            ooStr.flush();

            ObjectInputStream in =
                new ObjectInputStream(new ByteArrayInputStream(baoStr.toByteArray()));

            newObject=in.readObject();
        } catch (ClassNotFoundException ex) {
        } catch (IOException ex) {
        } finally {
            try {
                ooStr.close();
            } catch (IOException ex) {
            }
        }
        return newObject;
    }
}

Usage:

MyObject obj2 = (MyObject) Clone.clone(obj1);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s