Java Serialization Series tutorial (top)

Source: Internet
Author: User
Tags object serialization serialization

A definition and related concepts

The emergence of the internet has brought about the need for inter-machine communication, and both parties to the interconnected communication are required to adopt agreed protocols, which are part of the communication protocol. Communication protocols often adopt a layered model, each layer of different models of functional definition and granularity, for example: TCP/IP protocol is a four-layer protocol, and the OSI model is a seven-layer protocol model. The main function of the Presentation layer in the OSI seven-layer protocol model is to convert the object of the application layer into a contiguous binary string, or vice versa, to convert the binary string into an application-level object, and the two functions are serialization and deserialization. In general, the application layer of the TCP/IP protocol corresponds to the application layer, the presentation layer, and the session layer of the OSI Seven layer protocol model, so the serialization protocol is part of the application layer of the TCP/IP protocol. In this paper, the interpretation of serialization protocol is based on OSI seven layer protocol model.

    • Serialization: The process of converting a data structure or object into a binary string.

    • Deserialization: The process of converting a binary string generated during serialization into a data structure or object.

Two scenario 2.1 Object persistence

The Java platform allows us to create reusable Java objects in memory, but in general, these objects can exist only when the JVM is running, that is, they will not have a longer life cycle than the JVM. In a real-world application, however, it is possible to require that the specified object be saved (persisted) after the JVM has stopped running, and that the saved object will be re-read in the future. The serialization of Java objects can help us implement this functionality. In the actual production scenario will use the cache in many cases, the use of Redis to implement the cache know that when the data in the cache, whether it is key or value to complete the serialization, only after serialization to rely on Redis to store, when the data to be deserialized.

2.2 Object Network Transmission

When using RMI (remote method calls) in practice, such as Hession calls, Dubbo calls, or passing objects in the network, object serialization and deserialization are used.

Three how to implement serialization

In Java, as long as a class implements the Java.io.Serializable interface, it can be serialized. First define a user class.

1Package com.duomeng.product;
2Import java.io.*;
3PublicClassUserImplementsserializable{
4PrivateStaticFinalLong Serialversionuid =-6513548580766215238L;
5public String name;
6Public String Pawssword;
7     public String getName () {
8         Retu RN name;
9    }
    public void setName (String name) {
        this.name = name;
   }
    public String Getpawssword () {
+         return pawssword;
   }
    public void Setpawssword (String pawssword) {
17         this.pawssword = Pawssword;
   }

Then write a test class to complete the serialization and deserialization test, defined as Usertest.class

1package com.duomen.product;
2import java.io.*;
3PublicClassusertest {
4PublicStaticvoidMainString[] (args) {
5 User User =New User ();
6 User.setname ("Duomeng");
7 User.setpawssword ("123qwe");
8try {
9Serialization of
Ten ObjectOutputStream ObjectOutputStream =New ObjectOutputStream (New FileOutputStream ("User.obj"));
Objectoutputstream.writeobject (user);
Objectoutputstream.flush ();
Objectoutputstream.close ();
14Deserialization
ObjectInputStream ObjectInputStream =New ObjectInputStream (New FileInputStream ( "User.obj"));
           user olduser = (User) objectinputstream.readobject ();
           objectinputstream.close ();
           system. Out.println ( "name = [" + olduser.getname () + "]");
           system. out.println ( "password = [" + Olduser.getpawssword () + "]");
       } catch (IOException e) {
           e.printstacktrace ();
       } catch (ClassNotFoundException e) {
           e.printstacktrace ();
       }
   }

If there is no problem, then the results will be expected to output the following content

1name = [duomeng]
2password = [123qwe]

Four related knowledge

1. Serialization and deserialization of objects via ObjectOutputStream and ObjectInputStream

2. If an instance of a class is instantiated, Then this class must implement Java.io.Serializable, and no java.io.NotSerializableException exception will be thrown when instantiated, because there is probably the following call column WriteObject in the process of serialization--- > WRITEOBJECT0--->writeordinaryobject--->writeserialdata--->invokewriteobject, Take a look at some of the code in the WriteObject0 method, as follows

1Remaining cases
2if (objinstanceofString) {
3 WriteString ((String) obj, unshared);
4}Elseif (Cl.isarray ()) {
5 Writearray (obj, desc, unshared);
6}Elseif (objInstanceof Enum) {
7 Writeenum ((enum<?>) obj, desc, unshared);
8}Elseif (objInstanceof Serializable) {
9 Writeordinaryobject (obj, desc, unshared);
Ten} else {
if (extendeddebuginfo) {
throw New Notserializableexception (
Cl.getname () + "\ n" + debuginfostack.tostring ());
+} Else {
New Notserializableexception (Cl.getname ());
16}
+ }

3. Whether the virtual machine allows deserialization, not only depends on the class path and function code consistency, a very important point is whether the serialization ID of the two classes is consistent (that is, private static final long Serialversionuid) if the specified serialization ID is not displayed , the JVM calculates a serialversionuid based on the properties and methods of the class of the current object during serialization, as well as when deserializing a serialversionuid based on the properties and methods of the target class, if after serialization, The property or method of the corresponding class changes so that the computed serialversionuid is not the same, so that when deserializing, the exception is thrown, the deserialization fails, and the usual practice is to display the generated by the IDE, This not only prevents the modification of the class's properties or methods from causing the deserialization to fail, but can also rely on serialversionuid to restrict access, such as changing the Serialversionuid, Those who do not know the latest serialversionuid will fail.

4. To serialize the parent class object, you need to have the parent class also implement the Java.io.Serializable interface, otherwise the properties of the parent class will not complete serialization.

Five summary

There are many implementations of serialization in practical applications, such as JSON and XML, which are commonly used, as well as serialization, as the beginning of the process of converting a data structure or object into a binary string is called serialization. The process of converting the binary string generated during serialization to a data structure or object is deserialized.

Java Serialization Series tutorial (top)

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.