1. public class MyUtil {
    2. /**
    3. * 通过序列化实现深度克隆
    4. * 先序列化对象到内存
    5. * 再反序列化对象并返回
    6. *
    7. * @param obj
    8. * @param <T>
    9. * @return
    10. * @throws Exception
    11. */
    12. public static <T extends Serializable> T clone(T obj) throws Exception {
    13. /**
    14. * 先序列化对象到内存
    15. */
    16. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    17. ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
    18. objectOutputStream.writeObject(obj);
    19. /**
    20. * 反序列对象并返回
    21. */
    22. ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());
    23. ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
    24. return (T) objectInputStream.readObject();
    25. }
    26. }