public class MyUtil {
/**
* 通过序列化实现深度克隆
* 先序列化对象到内存
* 再反序列化对象并返回
*
* @param obj
* @param <T>
* @return
* @throws Exception
*/
public static <T extends Serializable> T clone(T obj) throws Exception {
/**
* 先序列化对象到内存
*/
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(obj);
/**
* 反序列对象并返回
*/
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
return (T) objectInputStream.readObject();
}
}