What is object serialization?

前端 未结 14 2119
长发绾君心
长发绾君心 2020-11-21 23:23

What is meant by \"object serialization\"? Can you please explain it with some examples?

14条回答
  •  借酒劲吻你
    2020-11-22 00:01

    Serialization is the process of saving an object in a storage medium (such as a file, or a memory buffer) or to transmit it over a network connection in binary form. The serialized objects are JVM independent and can be re-serialized by any JVM. In this case the "in memory" java objects state are converted into a byte stream. This type of the file can not be understood by the user. It is a special types of object i.e. reused by the JVM (Java Virtual Machine). This process of serializing an object is also called deflating or marshalling an object.

    The object to be serialized must implement java.io.Serializable Interface. Default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields.

    class ObjectOutputStream extends java.io.OutputStream implements ObjectOutput,
    

    ObjectOutput interface extends the DataOutput interface and adds methods for serializing objects and writing bytes to the file. The ObjectOutputStream extends java.io.OutputStream and implements ObjectOutput interface. It serializes objects, arrays, and other values to a stream. Thus the constructor of ObjectOutputStream is written as:

    ObjectOutput ObjOut = new ObjectOutputStream(new FileOutputStream(f));
    

    Above code has been used to create the instance of the ObjectOutput class with the ObjectOutputStream( ) constructor which takes the instance of the FileOuputStream as a parameter.

    The ObjectOutput interface is used by implementing the ObjectOutputStream class. The ObjectOutputStream is constructed to serialize the object.

    Deserializing an Object in java

    The opposite operation of the serialization is called deserialization i.e. to extract the data from a series of bytes is s known as deserialization which is also called inflating or unmarshalling.

    ObjectInputStream extends java.io.InputStream and implements ObjectInput interface. It deserializes objects, arrays, and other values from an input stream. Thus the constructor of ObjectInputStream is written as:

    ObjectInputStream obj = new ObjectInputStream(new FileInputStream(f));
    

    Above code of the program creates the instance of the ObjectInputStream class to deserialize that file which had been serialized by the ObjectInputStream class. The above code creates the instance using the instance of the FileInputStream class which holds the specified file object which has to be deserialized because the ObjectInputStream() constructor needs the input stream.

提交回复
热议问题