import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;import java.util.Date;
public class Person implements Cloneable,Serializable{
private int id;
private String name;
private int age;
private Date brith;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBrith() {
return brith;
}
public void setBrith(Date brith) {
this.brith = brith;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age
+ ", brith=" + brith + ", address=" + address + "]";
}
/**
* 浅克隆
*
* @return
* @throws CloneNotSupportedException
*/
public Person myclone()throws CloneNotSupportedException{
return (Person) super.clone();
}
/**
* 深克隆
* @return
* @throws CloneNotSupportedException
* @throws IOException
* @throws ClassNotFoundException
*/
public Person deepclone()throws CloneNotSupportedException, IOException, ClassNotFoundException{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
Person p = (Person) ois.readObject();
return p;
}
}
*********************************** 测试 ***********************************
package com.lovo.prototype;
import java.io.IOException;
import java.util.Date;
public class Test {
public static void main(String[] args) throws CloneNotSupportedException, IOException, ClassNotFoundException {
Person p = new Person();
p.setId(1);
p.setName("张三");
p.setAge(18);
p.setBrith(new Date());
p.setAddress("四川省成都市武侯区");
Person p2 = p.deepclone();
p2.setName("李四");
p2.setAge(20);
System.out.println(p);
System.out.println("**************************************************");
System.out.println(p2);
}
}