java对象序列化readObject / defaultReadObject [英] java object serialization readObject/defaultReadObject

查看:137
本文介绍了java对象序列化readObject / defaultReadObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ObjectInputStream readObject defaultReadObject 之间的区别是什么? c>上课?我似乎无法找到有关差异的大量信息。

What's the difference between readObject and defaultReadObject in the ObjectInputStream class? I can't seem to find very much information on the difference.

推荐答案

defaultReadObject()调用默认的反序列化机制,并在 Serializable readObject()方法时使用>上课。换句话说,当您具有自定义反序列化逻辑时,您仍然可以返回到默认序列化,这将反序列化非静态非瞬态字段。例如:

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:

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();
    }
]






另一方面,从反序列化对象外部创建 ObjectInputStream 时,使用 readObject(),并且想要读取先前序列化的对象:


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:

ObojectInputStream stream = new ObjectInputStream(aStreamWithASerializedObject);
Object foo = (Foo) stream.readObject();

这篇关于java对象序列化readObject / defaultReadObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆