今天在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";
}
}