Serializable implementation without providing writeObject / readObject method

What if the class implements a serializable interface, but there is no method implementation writeObject/readObjectsomewhere in the code base?

Will the default methods defaultWriteObject/defaultReadObjectserialize or not?

Is just the class of the class implements Serializablesufficient to serialize the class?

If so, what happens to serialization and where does the state of the object persist?

+4
source share
3 answers

What if the class implements a serializable interface, but there is no method implementation writeObject/readObjectsomewhere in the code base?

It will be serialized by default: see below.

Will the default methods defaultWriteObject/defaultReadObjectserialize or not?

No, because they will not be called unless you call them.

Is just the class of the class implements Serializablesufficient to serialize the class?

Yes, if you are satisfied with the default serialization: see below.

,

- , Serializable, .

?

. , , ,

+3

1) defaultWriteObject/defaultReadObject ? -NO,

defaultReadObject() , readObject() Serializable. , , , , . :

public class TestClass implements Serializable {
    private String f2;
    private int f1;
    private transient String f3; 
    private void readObject(java.io.ObjectInputStream stream)
         throws IOException, ClassNotFoundException {
         stream.defaultReadObject(); //fills f1 and f2;
         fld3 = Configuration.getFooConfigValue();
    }
}

, readObject() , ObjectInputStream, , , :

ObojectInputStream stream = new ObjectInputStream(aStreamWithASerializedObject);
Object foo = (Foo) stream.readObject();

java.io.ObjectOutputStream.defaultWriteObject() . writeObject , , . out.defaultWriteObject(), .

2) Serializable ? ,

, java.io.Serializable, . , , , , . , .

, , OutputStream, , . , java.io.ObjectOutputStream, OutputStream.

/ Write to disk with FileOutputStream
FileOutputStream f_out = new 
    FileOutputStream("myobject.data");

// Write object with ObjectOutputStream
ObjectOutputStream obj_out = new
    ObjectOutputStream (f_out);



 // Write object out to disk
    obj_out.writeObject ( myObject );

3) , ? - , Serializable, - media/file.object , , .

+1

https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html

, , , .

writeObject , readObject . Object out.defaultWriteObject. , . ObjectOutputStream writeObject , DataOutput.

readObject . in.defaultReadObject . defaultReadObject , , . , , . , . ObjectOutputStream writeObject , DataOutput.

readObjectNoData , . , , , - , . , ; , readObjectNoData , "" .

0

Source: https://habr.com/ru/post/1621072/


All Articles