一、serialVersionUID
- 问:用对象序列化流序列化了一个对象后,假如我们修改了对象所属的类文件,读取数据会不会出问题呢?
- 答:会出问题,会抛出InvalidClassException异常
- 问:如果出问题了,如何解决呢?
- 答
- 重新序列化
- 给对象所属的类加一个serialVersionUID
二、transient
- 问:如果一个对象中的某个成员变量的值不想被序列化,又该如何实现呢?
- 答:给该成员变量加transient关键字修饰,该关键字标记的成员变量不参与序列化过程
三、实例
public class Student implements Serializable {
private static final long serialVersionUID = 42L;
private String name;
private transient int age;
public Student(){}
public Student(String name, int age){
this.name = name;
this.age = age;
}
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 class Test{
public static void main(String[] args) throws IOException, ClassNotFoundException {
read();
return;
}
private static void read() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("oos.txt"));
Object obj = ois.readObject();
Student s = (Student) obj;
System.out.println(s.getName()+","+s.getAge());
ois.close();
}
private static void write() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("oos.txt"));
Student s= new Student("EuropeanSheik",30);
oos.writeObject(s);
oos.close();
}
}