/* Copyright 2000 by Basil Vandegriend.  All rights reserved. */

package com.basilv.core;

import java.io.*;

/**
 * A generic approach for cloning Serializable objects by serializing and
 * deserializing them.
 */
public class SerializerCloner
{

	/**
	 * Return an object that is a clone of the specified target. The clone is
	 * created by serializing and then deserializing the target object. The
	 * clone will usually be a deep copy, although in general the exact nature
	 * of the cloning will depend on how the specified target and its contained
	 * objects are serialized.
	 * 
	 * @param target the object to clone. Cannot be null.
	 * @return the cloned object.
	 * @throws RuntimeException if problems occur in doing the serialization.
	 */
	public static Object clone(Serializable target) {
		Assert.notNull("target", target);

		try {
			ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
			ObjectOutputStream objectOutputer = new ObjectOutputStream(byteOutputStream);
			objectOutputer.writeObject(target);
			objectOutputer.close();
			byteOutputStream.close();

			ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteOutputStream.toByteArray());
			ObjectInputStream objectInputer = new ObjectInputStream(byteInputStream);
			Object clonedTarget = objectInputer.readObject();
			return clonedTarget;
		} catch (Exception e) {
			throw new RuntimeException("Error cloning object via serialization.", e);
		}
	}
	
}
