Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2290028
  • 博文数量: 266
  • 博客积分: 5485
  • 博客等级: 大校
  • 技术积分: 3695
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-20 11:05
个人简介

多读书,多做事,广交朋友,趣味丛生

文章分类

全部博文(266)

分类: Java

2012-03-13 20:25:21

    最近的系统改造,遇到了前人写的PropertyUtilsBean.( dest, orig)
方法来复制对象,想到自己对Java API了解到太少,以后可以多多学习。
    由于改造后的系统运用JPA技术,将以前的JOPO转换成了实体Bean,并且实体Bean间建立起了表之间的关联关系(一对多、多对一、多对多之乎者也的),调试程序时发现copyProperties方法失效了,不解之下,找到了JavaSE的API一窥究竟,原来该方法不支持续对象的嵌套复制,API中如是说:

Note that this method is intended to perform a "shallow copy" of the properties and so complex properties (for example, nested ones) will not be copied.

Note, that this method will not copy a List to a List, or an Object[] to an Object[]. It's specifically for copying JavaBean properties.

    于是在网上借鉴了用输入输出流进行深度复制的方法,问题终于解决了,在此感谢豁然开朗的代码:

点击(此处)折叠或打开

  1. private static Object depthClone(Object srcObj){
  2. 74. Object cloneObj = null;
  3. 75. try {
  4. 76. ByteArrayOutputStream out = new ByteArrayOutputStream();
  5. 77. ObjectOutputStream oo = new ObjectOutputStream(out);
  6. 78. oo.writeObject(srcObj);
  7. 79.
  8. 80. ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
  9. 81. ObjectInputStream oi = new ObjectInputStream(in);
  10. 82. cloneObj = oi.readObject();
  11. 83. } catch (IOException e) {
  12. 84. e.printStackTrace();
  13. 85. } catch (ClassNotFoundException e) {
  14. 86. e.printStackTrace();
  15. 87. }
  16. 88. return cloneObj;
  17. 89. }


 


 
 
阅读(5506) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~