java object serialization readObject/defaultReadObject

前端 未结 1 935
忘掉有多难
忘掉有多难 2020-12-11 15:35

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

相关标签:
1条回答
  • 2020-12-11 16:25

    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 讨论(0)
提交回复
热议问题