Crazy Java Learning Note (------------) serialization of objects

Source: Internet
Author: User
Tags object serialization

   The so-called object serialization is to convert the state of an object into a byte stream, which can then be used to generate objects of the same state!        object Serialization is an implementation of object persistence, which transforms the properties and methods of an object into a serialized format for storage and transport, and deserialization is the process of rebuilding an object based on these saved information.  The Java object Serialization mechanism generally has two uses :
1. You need to save the state of the object to a file (store), and then be able to reconstruct the object by reading the state of the object, restoring the state of the program
2. It is useful for programs that use sockets to transfer objects over a network.
we can serialize the class by letting the class implement the Java.io.Serializable interface. This interface is a manufacturer (marker) interface. That is, the interface does not need to implement any methods for the class to implement it. It is primarily used to inform the Java Virtual Machine (JVM) that an object needs to be serialized.
for this, there are a few things we need to make clear:
1. Not all classes can be serialized, under CMD, we enter Serialver Java.net.socket, we can get the information that the socket can be serialized, in fact, the socket is not serializable.
2.java has many basic classes that have implemented serializable interfaces, such as String,vector. But for example, Hashtable does not implement the serializable interface.
There are two main classes that read or write to a stream: ObjectOutputStream and ObjectInputStream. The ObjectOutputStream provides a writeobject method for writing objects to the output stream, ObjectInputStream provides a ReadObject method for reading objects from the input stream. Objects that use these methods must already be serialized . in other words, the serializable interface must already be implemented. If you want to writeobject a Hashtable object, you get an exception.  in many applications, some objects need to be serialized to leave the memory space and stay on the physical hard disk for long-term storage. For example, the most common is the Web server session object, when there are 100,000 users concurrent access, there may be 100,000 session objects, memory may be unbearable, so the Web container will be some seesion first serialized to the hard disk, and so on, Restore the objects that were saved to the hard disk in memory.  when two processes are communicating remotely, each other can send various types of data. Regardless of the type of data, it is transmitted over the network in the form of a binary sequence. The sender needs to convert the Java object to a sequence of bytes to be transmitted over the network, and the receiver needs to revert the byte sequence back to the Java object.   serialization APIs in the JDK class library  

Java.io.ObjectOutputStream represents an object output stream, and its writeobject (object obj) method serializes the Obj object specified by the parameter and writes the resulting sequence of bytes to a target output stream.
Java.io.ObjectInputStream represents an object input stream, and its readobject () method reads a sequence of bytes from a source input stream, deserializes them into an object, and returns them.


Only objects of classes that implement the serializable and Externalizable interfaces can be serialized. The Externalizable interface inherits from the serializable interface, and the class that implements the Externalizable interface controls the serialization behavior entirely by itself, whereas classes that implement the serializable interface can take the default serialization method.


Object serialization consists of the following steps:
1) Create an object output stream, which can wrap a different type of target output stream, such as a file output stream;
2) writes an object through the WriteObject () method of the object output stream.

The steps for deserializing an object are as follows:
1) Create an object input stream, which can wrap a different type of source input stream, such as a file input stream;
2) The object is read through the ReadObject () method of the object input stream.

Examples of object serialization and deserialization:

Define a person class to implement the Serializable interface

<span style= "FONT-SIZE:18PX;" >import java.io.serializable;/** * <p>ClassName:Person<p> * <p>description: Test object serialization and deserialization <p > * @author xudp * @version 1.0 V * @createTime 2014-6-9 pm 02:33:25 */public class Person implements Serializable {
   
    /**     * Serialization ID *     /    private static final long serialversionuid = -5809782578272943999l;    private int age;    private String name;    Private String sex;    public int getage () {        return age;    }    Public String GetName () {        return name;    }    Public String Getsex () {        return sex;    }    public void Setage (int.) {        this.age = age;    }    public void SetName (String name) {        this.name = name;    }    public void Setsex (String sex) {        this.sex = sex;    }} </span>
   


Serializing and deserializing a person class object

<span style= "FONT-SIZE:18PX;" >import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import java.text.messageformat;/** * <p>classname:testobjserializeanddeserialize <p> * <p>description: Test object serialization and deserialization <p> * @author xudp * @version 1.0 V * @createTime 2014-6-9 03:17:25 */public class Testobjserializeanddeserialize {public static void main (string[] args) throws Exception {Serial Izeperson ();//Serialize Person object Person P = Deserializeperson ();//Reverse Sequence Perons object System.out.println (messageformat.form    At ("Name={0},age={1},sex={2}", P.getname (), P.getage (), P.getsex ())); }/** * Methodname:serializeperson * Description: Serialize Person Object * @author xudp * @throws Filenotfou Ndexception * @throws IOException */private static void Serializeperson () throws FileNotFoundException, IOException {person person * = new person ()        ;        Person.setname ("GaCl");        Person.setage (25);        Person.setsex ("male"); The ObjectOutputStream object output stream, which stores the person object in the E-drive's Person.txt file, completes the serialization operation of the Person object ObjectOutputStream oo = new ObjectOutput        Stream (New FileOutputStream ("E:/person.txt"));        Oo.writeobject (person); System.out.println ("Person object serialization succeeded!")        ");    Oo.close (); }/** * Methodname:deserializeperson * Description: Reverse Sequence perons Object * @author xudp * @return * @throw        S Exception * @throws IOException */private static person Deserializeperson () throws Exception, IOException {        ObjectInputStream ois = new ObjectInputStream (new FileInputStream (New File ("E:/person.txt"));        Person person = (person) ois.readobject (); System.out.println ("The person object is deserialized successfully!")        ");    return person; }}</spAn> 


The role of Serialversionuid

In simple terms, the serialization mechanism of Java verifies version consistency by judging the serialversionuid of the class at run time. When deserializing, the JVM compares the serialversionuid in the stream that is transmitted to the serialversionuid of the local corresponding entity (Class), and if the same is considered consistent, it can be deserialized, otherwise the serialized version inconsistency exception will occur. (InvalidCastException)

An example of a practical application:

To achieve the purpose of system interaction, we need entities that transfer objects across the network between systems (these objects generally include some data from the system)


Java serialization is a solution:
To interact between systems A and B, object A in a is first serialized, then transferred over the network to System B, deserialized in B, and then manipulated to take advantage of the data provided by object A.

However, to achieve such a solution to the original system has the following requirements:


There must be a completely consistent object model between the interacting systems, which requires a large change in the original system and does not meet our requirements.

Because the serialized data is in binary format, we cannot process the data or see what data it contains unless the binary data is deserialized into the object itself. "
Systems that require interaction are Java-based, because Java serialization can only be applied to Java systems.

The role of Serializable
Why does a class implement the Serializable interface and it can be serialized? In the example in the previous section, using ObjectOutputStream to persist an object, there is the following code in the class:

Crazy Java Learning Note (------------) serialization of objects

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.