赞
踩
Beanutils.copyProperties( )是浅拷贝,仅是拷贝类型相同并且类型为基本类型的字段,如果是引用类型的话,则是拷贝引用地址,因此是浅拷贝。需要注意。
比如定义如下学生类
/** * 学生 */ public class Student implements Cloneable { private String name; private int age; // 引用对象 private Major major; @Override protected Object clone() throws CloneNotSupportedException { Student student = (Student) super.clone(); student.setMajor((Major) this.major.clone()); return student; } //.... }
/** * 学生 */ public class Student implements Serializable { private String name; private int age; private Major major; @Override protected Student clone() throws CloneNotSupportedException { try { // 将对象本身序列化到字节流 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream( byteArrayOutputStream ); objectOutputStream.writeObject( this ); // 再将字节流通过反序列化方式得到对象副本 ObjectInputStream objectInputStream = new ObjectInputStream( new ByteArrayInputStream( byteArrayOutputStream.toByteArray() ) ); return (Student) objectInputStream.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return null; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。