java通过序列化实现对象的深度克隆

2025-12-20 16:44:18

1、建立一个java工程,其基本目录见下图,小编采用的是eclipse软件。

java通过序列化实现对象的深度克隆

2、编写一个子类,该子类被我们要克隆的类引用,用以显示该深度克隆的意义。

class Address implements Serializable{

private String state;

private String privance;

private String city;

public Address(String state,String privance ,String city){

this.state=state;

this.privance=privance;

this.city=city;

}

public String getCity(){

return this.city;

}

public String getState(){

return this.state;

}

public String getPrivance(){

return this.privance;

}

public void setState(String state){

this.state=state;

}

public void setPrivance(String privance){

this.privance=privance;

}

public void setCity(String city){

this.city=city;

}

public String toString(){

StringBuilder sb=new StringBuilder();

sb.append("国窖:"+state+",");

sb.append("省:"+privance+",");

sb.append("市:"+city+",");

return sb.toString();

}

}

java通过序列化实现对象的深度克隆

3、编写要被克隆的类,该类就是我们要实现克隆的具体。

java通过序列化实现对象的深度克隆

4、编写我们的实验代码,该代码用于实现我们的一个克隆实例,具体如下图所示,代码如下:

public static void main(String[] args) {

System.out.println("序列化之前");

Address address=new Address("中国","吉林","长春");

Employees employee1=new Employees("小明", 30, address);

System.out.println("员工1的信息:");

System.out.println(employee1);

System.out.println("序列化之后:");

ObjectOutputStream out=null;

ObjectInputStream in=null;

Employees employee2=null;

try{

out=new ObjectOutputStream(new FileOutputStream("employees.dat"));

out.writeObject(employee1);

in=new ObjectInputStream(new FileInputStream("employees.dat"));

employee2=(Employees)in.readObject();

}catch(FileNotFoundException e){

e.printStackTrace();

}catch(IOException e){

e.printStackTrace();

}catch(ClassNotFoundException e){

e.printStackTrace();

}finally{

}

employee2.getAddress().setState("中国");

employee2.getAddress().setPrivance("四川");

employee2.getAddress().setCity("成都");

employee2.setName("大明");

employee2.setAge(24);

System.out.println("员工1的信息:");

System.out.println(employee1);

System.out.println("员工2的信息:");

System.out.println(employee2);

}

java通过序列化实现对象的深度克隆

5、查看效果,单击“编译运行”运行按钮,我们可以看到此深度克隆的实现效果,往细细思考。

java通过序列化实现对象的深度克隆

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢