2.8serialVersionUID&transient【应用】
-
serialVersionUID
-
用对象序列化流序列化了一个对象后,假如我们修改了对象所属的类文件,读取数据会不会出问题呢?
-
会出问题,会抛出InvalidClassException异常
-
-
如果出问题了,如何解决呢?
-
重新序列化
-
给对象所属的类加一个serialVersionUID
-
private static final long serialVersionUID = 42L;
-
-
-
-
transient
-
如果一个对象中的某个成员变量的值不想被序列化,又该如何实现呢?
-
给该成员变量加transient关键字修饰,该关键字标记的成员变量不参与序列化过程
-
-
-
示例代码
package duixiangxuliehua;
import java.io.Serial;
import java.io.Serializable;
public class Student implements Serializable {
@Serial
// 显示序列化id
private static final long serialVersionUID = 42L;
private String name;
// private int age;
// 不参与序列化
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;
}
/* @Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}*/
}
package duixiangxuliehua;
import java.io.*;
public class demo1 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// write();
read();
}
public static void write() throws IOException {
ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream("stu\\src\\duixiangxuliehua\\demo.txt"));
Student s = new Student("林青霞",30);
oo.writeObject(s);
oo.close();
}
public static void read() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("stu\\src\\duixiangxuliehua\\demo.txt"));
Object o = ois.readObject();
Student s = (Student) o;
System.out.println(s.getName()+s.getAge());
ois.close();
}
}