请参阅下面的剪辑
USPresident usPresident = new USPresident(56);
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("/home/nikhil/dev/USPresident.data"))){
oos.writeObject(usPresident);
usPresident.setTerm(57);
oos.writeObject(usPresident);
System.out.println("Serialized");
}
创建了一个总统实例,任期为56.
序列化它.
将术语重置为57
再次序列化
但是,当我反序列化对象时,它的术语仍为56(而不是57!)
我在书上看到了这个解释,
Yes, it will print 56 even though you changed the term using its
setter to 57 and serialized again. This happens due to
serialVersionUID, which is checked by the JVM at the time of
serialization. If a class is already serialized and you try to
serialize it again, the JVM will not serialize it.
但是,据我所知,serialVersionUID用于在反序列化期间检查Class对象是否与序列化对象匹配.此外,serialVersionUID用作Object签名的标识符,而不是状态.
不明白这里发生了什么.有人可以解释这种行为吗?
看一下ObjectOutputStream的实现,这就是writeObjet的实现方式
public final void writeObject(Object obj) throws IOException {
if (enableOverride) {
writeObjectOverride(obj);
return;
}
try {
writeObject0(obj, false);
} catch (IOException ex) {
if (depth == 0) {
writeFatalException(ex);
}
throw ex;
}
}
请参阅boolean enableOverride.写’修改’对象必须如此.但是,只有在使用ObjectOutputStream的子类时,才能将其设置为true.请参阅下面的受保护构造函数,
protected ObjectOutputStream() throws IOException, SecurityException {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
bout = null;
handles = null;
subs = null;
enableOverride = true;
debugInfoStack = null;
}
为什么这么奇怪的行为?