java的clone

作項目時有時可能會遇到須要克隆對象的時候,由於有時候對象是直接從別的類get到的,那樣引用的是一個對象,修改的話會將原先的對象也修改了。java

java的淺克隆,十分簡單。可是隻會克隆基本的數據類型,當涉及到引用類型時就很差用了。sql

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方法的。另外一種是經過序列化來進行克隆。this

第一種方法,須要將引用的類須要每一個都clone。spa

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();
 }
}
相關文章
相關標籤/搜索