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;
        }
    }
  • 相关阅读:
    gitlab的数据库磁盘坏了已经没有办法恢复情况下如何恢复git上的代码
    psql: FATAL: the database system is in recovery mode
    k8s 下 jenkins 分布式部署:利用pipeline动态增加slave节点
    pipeline 流水线:持续部署(docker)-企业微信群通知消息
    查看私有仓库镜像的版本列表
    MyBatis与Hibernate比较
    MyBatis与JDBC的对比
    Java_Ant详解(转载)
    IntelliJ Idea 常用快捷键列表
    隔行换色
  • 原文地址:https://www.cnblogs.com/JonaLin/p/11276117.html
Copyright © 2011-2022 走看看