我正在尝试理解java序列化机制,而且我没有什么疑问
请回答以下有关java序列化的问题:
oos.defaultWriteObject();
?根据this post,its在那里是为了向后兼容性。我也不太明白它是如何实现不兼容更改的that.one的,因为序列化是删除更新版本中的字段。这意味着旧版本必须设置默认值(有时对user.how无效),这与添加新字段并允许设置默认值的新版本有什么不同吗?oos.defaultWriteObject();
和oos.writeObject(address);
会有什么不同吗?我的意思是将所有超类和当前类的非瞬态非静态字段写入OOS。这里
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException {
stream.writeObject(name);
stream.writeInt(id);
stream.writeObject(DOB);
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
name = (String) stream.readObject();
id = stream.readInt();
DOB = (String) stream.readObject();
}
以上代码产生的结果与下面的代码相同
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException {
stream.defaultWriteObject();
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
}
何时使用这两个方法,何时只使用writeObject(employee);//employee是我的整个对象//
发布于 2019-12-25 10:12:16
请回答你的问题
writeObject
并不是为了向后兼容性。readObject
是。defaultWriteObject
帮助您快速编写“可序列化”值。后向兼容性
假设您的bean添加了一个新字段。
class Bean implements Serializable {
int id;
String name;
String newValue = "123";
}
尽管您已经给出了newValue
默认值,但是java序列化将忽略它。(因为它分配实例而不是new
)
现在,如果您不使用readObject
,您将得到newValue=null
。因此,您也需要在readObject
进行初始化。
private void readObject(ObjectInputStream stream) throws Exception {
stream.defaultReadObject();
this.newValue = "123";
}
defaultWriteObject
如何帮助你
考虑到除了某些字段之外,bean几乎是“可序列化的”。
请参见下面的代码。BadThing
不是Serializable
,或者它有一些您不想序列化的敏感数据。
class Bean implements Serializable {
int id;
String string;
BadThing badThing;
}
要快速序列化它,可以让字段transient
并编写writeObject
方法来处理它。
private void writeObject(ObjectOutputStream stream) throws Exception {
stream.defaultWriteObject();
stream.writeInt(badThing.id);
}
// Corresponding `readObject`
当然,您可以将defaultWriteObject
替换为几个writeXXX
。但是如果您有很多字段,那么编写代码是很累的,很无聊,对吧?
因此,defaultWriteObject
只是为了避免编写无聊的代码。
https://stackoverflow.com/questions/51960890
复制相似问题