对于Java的克隆技术,标准的方式是:首先实现Cloneable接口,然后重写clone方法,调用父类clone进行克隆。
介绍另外一种方法,该方法的原理:
利用流将序列化的对象写在流里,因为写在流里面的对象就是原对象的一份拷贝,而原对象还在Java虚拟机里(JVM)里,再从流里面读取出来得到的对象就是得到一份克隆对象。
注意:需要克隆的对象必须实现Serializable接口
接着之前的场景,看下面的例子:
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private String userName;
private Address address;
public User(String userName) {
super();
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Object copy() throws IOException, ClassNotFoundException{
//将对象序列化后写在流里,因为写在流里面的对象是一份拷贝,
//原对象仍然在JVM里
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
bos.toByteArray()));
return ois.readObject();
}
}
public class Address implements Serializable{
private static final long serialVersionUID = 1L;
private String addressName;
public Address(String addressName) {
super();
this.addressName = addressName;
}
public String getAddressName() {
return addressName;
}
public void setAddressName(String addressName) {
this.addressName = addressName;
}
}
/**
* 测试克隆-深克隆(使用序列化的方式进行深克隆)
* 深克隆不但克隆当前的对象,而且还克隆该对象所引用的对象
* @author CST
*/
public class TestClone {
public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
User chen = new User("CST");
chen.setAddress(new Address("福州"));
User liu = (User) chen.copy();
liu.setUserName("LXF");
liu.getAddress().setAddressName("泉州");
System.out.println(chen.getUserName()+"="+chen.getAddress().getAddressName());
}
}
输出结果:CST=福州
效果同实现Cloneable接口方式一样