您的位置:首页 > 其它

序列化与对象克隆

2017-03-18 11:12 337 查看
/**
* 序列化与对象克隆
* 如果累的成员变量比较复杂,使用了多个可变引用类型,使用clone()是非常麻烦的
* 此时可以考虑使用序列化的方式完成克隆
*/
public class Address2 implements Serializable{

private static final long serialVersionUID = 5495499216106272874L;
private String state;
private String province;
private String city;
public Address2(String state, String province, String city) {
this.state = state;
this.province = province;
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Address [state=" + state + ", province=" + province + ", city="
+ city + "]";
}

}
public class Employee2 implements Serializable {

private String name;
private int age;
//新增Address对象
private Address2 address;

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 Employee2(String name, int age) {
this.name = name;
this.age = age;
}
public Employee2(String name, int age, Address2 address) {
this.name = name;
this.age = age;
this.address = address;
}

public Address2 getAddress() {
return address;
}
public void setAddress(Address2 address) {
this.address = address;
}
public Employee2() {
}
@Override
public String toString() {
return "Employee [name=" + name + ", age=" + age + ", address="
+ address + "]";
}

}
测试如下:
public static void main(String[] args) throws CloneNotSupportedException, IOException {
System.out.println("序列化之前:");
Address2 address = new Address2("中国", "吉林", "长春");
Employee2 emp1 = new Employee2("张XX",30,address);
System.out.println("员工1的信息:"+emp1);
System.out.println("序列化之后:");

ObjectOutputStream out = null;
ObjectInputStream in = null;
Employee2 emp2 = null;
try {
//将对象写入本地
out = new ObjectOutputStream(new FileOutputStream("emp.dat"));
out.writeObject(emp1);
in = new ObjectInputStream(new FileInputStream("emp.dat"));
emp2 = (Employee2)in.readObject();
} catch (Exception e) {
e.printStackTrace();
}finally{
out.close();
in.close();
}

if(emp2 != null){
emp2.getAddress().setState("中国");
emp2.getAddress().setProvince("四川");
emp2.getAddress().setCity("成都");
emp2.setName("李XX");
emp2.setAge(24);
System.out.println("员工1的信息:"+emp1);
System.out.println("员工2的信息:"+emp2);
}
}
运行结果如下:


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  序列化 对象克隆