克隆工具类,进行深克隆,包括对象、集合
2023-09-27 14:24:43 时间
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; } }
相关文章
- JDBC数据库操作工具类——JdbcUtils
- CleanMyMac X真正好用的Mac电脑系统优化软件应用工具
- Linux自动化运维工具之ansible(一)
- 国外安全人员推荐的免费、好用的安全工具
- Python之数据库操纵工具
- Java8中的LocalDateTime工具类
- 用过的sql 工具
- Linux Shell 文本处理工具
- 2023-02-03 sysbench压测工具使用
- Java Collections:专为集合框架而生的工具类
- gulp自动化构建工具使用
- SPMT(SharePoint Migration Tool)SharePoint 迁移工具介绍
- C#最佳工具集合:IDE、分析、自动化工具等
- 【 java 集合】Collections工具类的使用
- 开发者工具conloseLog的使用
- 基于OpenCL的深度学习工具:AMD MLP及其使用详解
- 10 个Docker小工具
- 用Go语言编写一门工具的终极指南
- linux 无线网络配置工具wpa_supplicant与wireless-tools
- Java集合框架:Arrays工具类
- 我的Android进阶之旅------>Java文件大小转换工具类 (B,KB,MB,GB,TB,PB之间的大小转换)
- 【集合工具类】判断集合为空