示例只是简单说明序列化反序列化过程中属性值是可以改变的
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Person implements Serializable {
private String firstName;
private String lastName;
private int age;
private Person spouse;
public Person(String fn, String ln, int a) {
this.firstName = fn;
this.lastName = ln;
this.age = a;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public Person getSpouse() {
return spouse;
}
public void setFirstName(String value) {
firstName = value;
}
public void setLastName(String value) {
lastName = value;
}
public void setAge(int value) {
age = value;
}
public void setSpouse(Person value) {
spouse = value;
}
private void writeObject(ObjectOutputStream stream) throws IOException {
age = age << 2; //序列化的时候加密
stream.defaultWriteObject();
}
private void readObject(ObjectInputStream stream) throws IOException,
ClassNotFoundException {
stream.defaultReadObject(); //反序列化的时候解密
age = age >> 2;
}
public String toString() {
return "[Person:firstName=" + firstName + "lastName=" + lastName
+ "age=" + age + "spouse="
+ (spouse != null ? spouse.getFirstName() : "[null]") + "]";
}
}