java 类不能序列化_java – 无法序列化已经序列化的类?

请参阅下面的剪辑

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;

}

为什么这么奇怪的行为?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值