假设我序列化了下面的类(通过给字段 x
赋值,比如说 5
),并且在进行反序列化之前,我删除了字段 x
并添加一个新字段y
(int
或float
),结果会是什么?
我相信反序列化已成功完成并且字段 y
的值将是默认值,这是正确的吗?
如果这是正确的,如果 x
将在序列化时从持久对象到有状态对象的转换中,值会去哪里?
public class Cat implements Serializable{
private static final long serialVersionUID = 4231235177539824282L;
int x;
}
反序列化之前:
public class Cat implements Serializable{
private static final long serialVersionUID = 4231235177539824282L;
float/int y;
}
最佳答案
序列化规范详细说明了字段反序列化的内部工作原理(您可以在这里找到它:http://docs.oracle.com/javase/7/docs/platform/serialization/spec/input.html)
如果您浏览“readObject 方法”部分,它指出:
Any field of the object that does not appear in the stream is set to its default value. Values that appear in the stream, but not in the object, are discarded. This occurs primarily when a later version of a class has written additional fields that do not occur in the earlier version.
所以本质上,字段“x”在流中会有一些值,但会被丢弃并且字段“y”将设置为 0(默认值),因为它没有出现在流中。
关于java - 序列化和反序列化变量删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9682978/