Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java object serialization readObject/defaultReadObject

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

like image 353
Falmarri Avatar asked Nov 07 '10 19:11

Falmarri


People also ask

What is readObject and writeObject?

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 .

How do you override a readObject and writeObject in Java?

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.

What is the return type of readObject () method?

Return Value This method returns the object read from the stream.

Does serialization reduce size?

In some cases, the secondary intention of data serialization is to minimize the data's size which then reduces disk space or bandwidth requirements.


1 Answers

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();
like image 58
Bozho Avatar answered Oct 05 '22 02:10

Bozho