java的clone

时间:2023-03-09 14:27:30
java的clone

做项目时有时可能会遇到需要克隆对象的时候,因为有时候对象是直接从别的类get到的,那样引用的是一个对象,修改的话会将原先的对象也修改了。

java的浅克隆,十分简单。但是只会克隆基本的数据类型,当涉及到引用类型时就不好用了。

public class Employee implements Cloneable {
private String name;
private String gender;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Employee clone() throws CloneNotSupportedException {
return (Employee) super.clone();
}
}

实现深克隆的话有两种方法,一种就是引用的类也是实现了clone方法的。另一种是通过序列化来进行克隆。

第一种方法,需要将引用的类需要每个都clone。

public class Employee implements Cloneable {
private String name;
private String gender;
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Employee clone() throws CloneNotSupportedException {
Employee cloned = (Employee) super.clone();
cloned.birthday = (Date) birthday.clone();
return cloned;
}
}

第二种方法就不需要这么做了。

package clone;
import java.io.*;
import java.sql.Date;
public class Employee implements Serializable {
private static final long serialVersionUID = 4435396040456359326L;
private String name;
private String gender;
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
} public Object deepClone(Object obj) throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
}
}