欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入
最近的系统改造,遇到了前人写的PropertyUtilsBean.copyProperties(Object dest, Object 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.
于是在网上借鉴了用输入输出流进行深度复制的方法,问题终于解决了,在此感谢豁然开朗的代码:
点击(此处)折叠或打开
private static Object depthClone(Object srcObj){
74. Object cloneObj = null;
75. try {
76. ByteArrayOutputStream out = new ByteArrayOutputStream();
77. ObjectOutputStream oo = new ObjectOutputStream(out);
78. oo.writeObject(srcObj);
79.
80. ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
81. ObjectInputStream oi = new ObjectInputStream(in);
82. cloneObj = oi.readObject();
83. } catch (IOException e) {
84. e.printStackTrace();
85. } catch (ClassNotFoundException e) {
86. e.printStackTrace();
87. }
88. return cloneObj;
89. }
人之所以有一张嘴,而有两只耳朵,原因是听的要比说的多一倍。