What's the difference between readObject
and defaultReadObject
in the ObjectInputStream
class? I can't seem to find very much information on the difference.
writeObject method writes the byte stream in physical location. To use the default mechanism to save the state of object, use defaultWriteObject. readObject method is used to read byte stream from physical location and type cast to required class. To read the data by default mechanism we use defaultReadObject .
Override default serialization to add validation In this usecase, you can use defaultReadObject() and defaultWriteObject() inside readObject() and writeObject() methods – to enable default serialization and deserialization.
Return Value This method returns the object read from the stream.
In some cases, the secondary intention of data serialization is to minimize the data's size which then reduces disk space or bandwidth requirements.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With