一、 Beanutils.copyProperties( )是深拷贝还是浅拷贝?
Beanutils.copyProperties( )是浅拷贝,仅是拷贝类型相同并且类型为基本类型的字段,如果是引用类型的话,则是拷贝引用地址,因此是浅拷贝。需要注意。
二、java如何实现深拷贝
1. 通过clone实现深拷贝
比如定义如下学生类
/**
* 学生
*/
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;
}
//....
}
- 首先学生类需要实现cloneable接口,并且实现clone方法,再clone方法的时候,需要先调用super.clone(),这样可以把除了引用对象的数据进行拷贝一次。
- 在学生类中有定义引用类型Major, 因此需要再调用major对象.clone方法,需要注意空指针处理。
- 因此在major类上也要如同student类一样实现cloneable接口。
2. 通过Object序列化(实现Serializable接口)
/**
* 学生
*/
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;
}
}