1.用对象序列化流序列化了一个对象后,假如我们修改了对象所属的类文件,读取数据会不会出问题? 如果出问题了,如何解决?
2.如果一个对象中的某个成员变量的值不想被序列化,又该如何实现呢?
给成员变量加transient关键字修饰,该关键字标记的成员变量不参与序列化过程
创建一个Student类
package demo17;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int chinese;
private int math;
public Student() {
}
public Student(String name, int chinese, int math) {
this.name = name;
this.chinese = chinese;
this.math = math;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getSum() {
return this.getChinese() + this.getMath();
}
}
接着序列化Student类
package demo17;
import java.io.*;
public class Demo01ObjectStream {
public static void main(String[] args) throws IOException, ClassNotFoundException {
write();
read();
}
//序列化
private static void write() throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("src\\oos.txt"));
Student s1 = new Student("张三", 98, 50);
oos.writeObject(s1);
oos.close();
}
//反序列化
private static void read() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("src\\oos.txt"));
Object obj = ois.readObject();
Student s=(Student) obj;
System.out.println(s.getName() + "," + s.getChinese() + "," + s.getMath());
ois.close();
}
}
运行程序可以正常执行!
1.用对象序列化流序列化了一个对象后,假如我们修改了对象所属的类文件,读取数据会不会出问题?
接着在Student类中生成toString()方法
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", chinese=" + chinese +
", math=" + math +
'}';
}
发现出现异常
java.io.InvalidClassException:
demo17.Student; local class incompatible:
stream classdesc serialVersionUID = 7074576674008727580,
local class serialVersionUID = 7515218800045627898
显示serialVersionUID不同,解决方法就是给对象所属的类加一个值,
private static final long serialVersionUID = 42L;
然后重新运行程序,发现即使修改方法,也可以正常运行!
2.如果一个对象中的某个成员变量的值不想被序列化,又该如何实现呢?
比如math我不想让别人看到,那么就可以给成员变量加transient关键字修饰,该关键字标记的成员变量不参与序列化过程
最后附上完整代码
package demo17;
import java.io.Serializable;
public class Student implements Serializable {
private static final long serialVersionUID = 42L;
private String name;
private int chinese;
private transient int math;
public Student() {
}
public Student(String name, int chinese, int math) {
this.name = name;
this.chinese = chinese;
this.math = math;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
public int getSum() {
return this.getChinese() + this.getMath();
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", chinese=" + chinese +
", math=" + math +
'}';
}
}