可以克隆任意一个复杂的Java对象,被克隆的对象要实现序列化implements java.io.Serializable
比如该方法可以轻松的copy出一个 XML文件对象
// returns a deep copy of an object
public static <T> T deepCopy(T oldObj) throws Exception
{
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
// serialize and pass the object
oos.writeObject(oldObj);
oos.flush();
ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bin);
// return the new object
return (T) ois.readObject();
}
catch(Exception e)
{
throw(e);
}
finally
{
if(oos != null) oos.close();
if(ois != null) ois.close();
}
}