利用Serialization实现对象深拷贝

本文介绍了一种通过序列化实现Java对象深拷贝的方法。具体步骤为:将原始对象写入字节流,再从该字节流中读取复制的对象。此方法适用于实现了Serializable接口的对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java 代码
 
  1. private PersonAggregateData copyAggregate(PersonAggregateData original) throws EventsPersonManagementException {  
  2.       
  3.     ByteArrayOutputStream outputBytes = new ByteArrayOutputStream();  
  4.     ObjectOutputStream out = null;  
  5.     ObjectInputStream in = null;  
  6.     PersonAggregateData copy;  
  7.     try {  
  8.         out = new ObjectOutputStream(outputBytes);  
  9.         ByteArrayInputStream inputBytes;  
  10.         out.writeObject(original);  
  11.   
  12.         inputBytes = new ByteArrayInputStream(outputBytes.toByteArray());  
  13.         in = new ObjectInputStream(inputBytes);  
  14.         copy = (PersonAggregateData) in.readObject();  
  15.     } catch (IOException e) {  
  16.         throw new EventsPersonManagementException("errors occur while copying the PersonAggregateData", e);  
  17.     } catch (ClassNotFoundException e) {  
  18.         throw new EventsPersonManagementException("errors occur while copying the PersonAggregateData", e);  
  19.     } finally {  
  20.         try {  
  21.             if (out != null) {  
  22.                 out.close();  
  23.             }  
  24.             if (in != null) {  
  25.                 in.close();  
  26.             }  
  27.         } catch (IOException e) {  
  28.             throw new EventsPersonManagementException("errors occur while copying the PersonAggregateData", e);  
  29.         }  
  30.     }  
  31.     return copy;  
  32. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值