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();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…