zoukankan      html  css  js  c++  java
  • 克隆工具类,进行深克隆,包括对象、集合

    package com.JUtils.clone;
    
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.util.Collection;
    
    /**
     * 克隆工具类,进行深克隆,包括对象、集合
     *
     */
    public class CloneUtils {
    
        /**
         * 采用对象的序列化完成对象的深克隆
         * @param obj
         *             待克隆的对象
         * @return
         */
        @SuppressWarnings("unchecked")
        public static <T extends Serializable> T cloneObject(T obj) {
            T cloneObj = null;
            try {
                // 写入字节流
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ObjectOutputStream obs = new ObjectOutputStream(out);
                obs.writeObject(obj);
                obs.close();
    
                // 分配内存,写入原始对象,生成新对象
                ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray());
                ObjectInputStream ois = new ObjectInputStream(ios);
                // 返回生成的新对象
                cloneObj = (T) ois.readObject();
                ois.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return cloneObj;
        }
    
        /**
         * 利用序列化完成集合的深克隆
         *
         * @param collection
         *                     待克隆的集合
         * @return
         * @throws ClassNotFoundException
         * @throws java.io.IOException
         */
        @SuppressWarnings("unchecked")
        public static <T> Collection<T> cloneCollection(Collection<T> collection) throws ClassNotFoundException, IOException{
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(collection);
            out.close();
    
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream in = new ObjectInputStream(byteIn);
            Collection<T> dest = (Collection<T>) in.readObject();
            in.close();
    
            return dest;
        }
    }
  • 相关阅读:
    SQL语句快速入门
    分享一些不错的sql语句
    放弃一键还原GHOST!!使用强大WIN7自带备份
    ZEND快捷方式
    eWebEditor在IE8,IE7下所有按钮无效之解决办法
    MySQL中文乱码解决方案集锦
    A+B Problem II(高精度运算)
    矩形嵌套(动态规划)
    贪心——会场安排
    擅长排列的小明(递归,暴力求解)
  • 原文地址:https://www.cnblogs.com/JonaLin/p/11276117.html
Copyright © 2011-2022 走看看