java深克隆

 /**
     * 使用对象的序列化进而实现深拷贝
     * @param obj
     * @param <T>
     * @return
     */
    private <T extends Serializable> T clone(T obj) {
        T cloneObj = null;
        try {
            ByteOutputStream bos = new ByteOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.close();
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            cloneObj = (T) ois.readObject();
            ois.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cloneObj;
    }

 

posted @ 2021-03-25 11:09  照旧  阅读(37)  评论(0编辑  收藏  举报