开发者

java object serialization readObject/defaultReadObject

What's the difference between readObject and defaultReadObject in the ObjectI开发者_StackOverflownputStream class? I can't seem to find very much information on the difference.


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

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜