序列化机制提供了一种克隆对象的简便途径,但是很慢!!!!
package xml;
import java.io.Serializable;
import java.util.Date;
import java.util.GregorianCalendar;
import java.io.*;
public class SerialCloneTest {
public static void main(String[] args){
Employee harry=new Employee("harry",2900,1989,1,1);
Employee newH=(Employee)harry.clone();
System.out.println(newH);
}
}
class SerialCloneable implements Serializable,Cloneable{
public Object clone(){
try{
ByteArrayOutputStream bout=new ByteArrayOutputStream();
ObjectOutputStream out=new ObjectOutputStream(bout);
out.writeObject(this);
out.close();
ByteArrayInputStream bin=new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in=new ObjectInputStream(bin);
Object ret=in.readObject();
in.close();
return ret;
}catch(Exception e){
return null;
}
}
}
class Employee extends SerialCloneable{
private String name;
private double salary;
private Date hireDay;
public Employee(){}
public Employee(String n,double s,int y,int m,int d){
this.name=n;
this.salary=s;
GregorianCalendar calendar=new GregorianCalendar(y,m-1,d);
this.hireDay=calendar.getTime();
}
public String getName(){
return this.name;
}
public double getSalary(){
return this.salary;
}
public Date getHireDay(){
return this.hireDay;
}
public String toString(){
return getClass().getName()+"[name="+name+",salary="+this.salary+",hireday="+this.hireDay+"]";
}
}