今天在sf上看到关于java序列化的一个方法,作用问题。
readObjectNoData>>问题链接
不明所以然,于是google了下。
后来题主给了我一个链接才看懂。于是自己试了一下,这里做一下记录。
这里有stackoverflown的一个相关问题,不过都是英文,但是其中一个回答,在我看了上面一个链接用例之后,结合这个就看懂了。
"Extendable" means "can have a subclass".
readObjectNoData is used in an unusual case where the serializer (writer) is working with a version of a class with no base class, whereas the deserializer (reader) of the class has a version of the class that IS based on a subclass. The subclass can say "it's ok if my base class isn't in the serialized data - just make an empty one" by implementing readObjectNoData. See theserelease notes.
还是修改后的代码:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class SerializeTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Persons p = new Persons();
p.setAge(10);
ObjectOutputStream oos;
try {
//先对旧的类对象进行序列化
oos = new ObjectOutputStream(new FileOutputStream("./person.ser"));
oos.writeObject(p);
oos.flush();
oos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Persons implements Serializable {
private int age;
public Persons() {}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class SerializeTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Persons p = new Persons();
p.setAge(10);
ObjectOutputStream oos;
try {
//用新的类规范来反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./person.ser"));
Persons sp = (Persons) ois.readObject();
System.out.println(sp.getName());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//新的类继承了animals,这是已经序列化的旧对象里面所没有的内容,
//所以实现readObjectNoData,可以弥补这种因临时扩展而无法兼容反序列化的缺陷
class Persons extends Animals implements Serializable {
private int age;
public Persons() { }
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
}
class Animals implements Serializable {
private String name;
public Animals() { }
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
private void readObjectNoData() {
this.name = "zhangsan";
}
}
本文详细解释了Java序列化中readObjectNoData方法的用途,特别是在处理子类与父类版本不一致时的解决策略。通过实例演示,深入理解其在扩展类时的反序列化兼容性问题。
645

被折叠的 条评论
为什么被折叠?



