java的淺克隆,十分簡單。可是隻會克隆基本的數據類型,當涉及到引用類型時就很差用了。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方法的。另外一種是經過序列化來進行克隆。sql
第一種方法,須要將引用的類須要每一個都clone。this
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; } }
第二種方法就不須要這麼作了。code
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(); } }