java java对象序列化readObject/defaultReadObject
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4119181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java object serialization readObject/defaultReadObject
提问by Falmarri
What's the difference between readObject
and defaultReadObject
in the ObjectInputStream
class? I can't seem to find very much information on the difference.
什么之间的区别readObject
,并defaultReadObject
在ObjectInputStream
上课吗?我似乎无法找到有关差异的太多信息。
回答by Bozho
defaultReadObject()
invokes the default deserialization mechanism, and is used when you define the readObject()
method on your Serializable
class. In other words, when you have custom deserialization logic, you can still get back to the default serialization, which will deserialize your non-static, non-transient fields. For example:
defaultReadObject()
调用默认的反序列化机制,并在您readObject()
在Serializable
类上定义方法时使用。换句话说,当您有自定义反序列化逻辑时,您仍然可以返回到默认序列化,这将反序列化您的非静态、非瞬态字段。例如:
public class SomeClass implements Serializable {
private String fld1;
private int fld2;
private transient String fld3;
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject(); //fills fld1 and fld2;
fld3 = Configuration.getFooConfigValue();
}
]
On the other hand, readObject()
is used when you create the ObjectInputStream
, externally from the deserialized object, and want to read an object that was previously serialized:
另一方面,readObject()
当您ObjectInputStream
从反序列化对象外部创建, 并且想要读取先前序列化的对象时使用:
ObojectInputStream stream = new ObjectInputStream(aStreamWithASerializedObject);
Object foo = (Foo) stream.readObject();