Java serialization and deserialization, Java serialization

Source: Internet
Author: User
Tags object serialization

Java serialization and deserialization, Java serialization

1. What is serialization? Why serialization?

JavaSerializationIt refers to the process of converting an object into a byte sequence, andDeserializationThe process of converting the byte sequence to the target object only.

We all know that the text, images, audios, and videos we see are transmitted in binary sequence during browser access, if we need to transmit a Java object, should we also serialize the object first? The answer is yes. We need to serialize the Java object first, and then transmit it through the network and IO. After arriving at the destination, We Need To deserialize it to get the object we want, finally, complete the communication.

 

2. How to Implement serialization

2.1 use the key classes ObjectOutputStream and ObjectInputStream in JDK

    In the ObjectOutputStream class, the Object is written in binary format by using the writeObject (object Object) method.

In the ObjectInputStream class, read binary streams from the input stream and convert them to objects by using the readObject () method.

 

 2.2. ObjectivesThe object must implement the Seriable interface first.

  

Create a Student class:

public class Student implements Serializable {    private static final long serialVersionUID = 3404072173323892464L;    private String name;    private transient String id;    private String age;    @Override    public String toString() {        return "Student{" +                "name='" + name + '\'' +                ", id='" + id + '\'' +                ", age='" + age + '\'' +                '}';    }    public String getAge() {        return age;    }    public void setAge(String age) {        this.age = age;    }    public Student(String name, String id) {        System.out.println("args Constructor");        this.name = name;        this.id = id;    }    public Student() {        System.out.println("none-arg Constructor");    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }}

 

        

In the code, the Student class implements the Serializable interface and generates a version number:

private static final long serialVersionUID = 3404072173323892464L;

First:

1,Serializable InterfaceThe function is only used to identify that our class needs to be serialized, And the Serializable interface does not provide any method.

2,SerialVersionUidThe serialization version number is used to identify the version of the class we have written and determine whether the version of the class is consistent during deserialization. if the version is inconsistent, an exception occurs.

3,Transient keywordTo ignore variables that we do not want to serialize.

 

    2.3. sequence or deserialize objects

2.3.1 first write mode:

Public static void main (String [] args) {File file = new File ("D:/test.txt"); Student student = new Student ("Sun Wukong", "12 "); try {ObjectOutputStream outputStream = new ObjectOutputStream (new FileOutputStream (file); outputStream. writeObject (student); outputStream. close ();} catch (IOException e) {e. printStackTrace ();} try {ObjectInputStream objectInputStream = new ObjectInputStream (new FileInputStream (file); Student s = (Student) objectInputStream. readObject (); System. out. println (s. toString (); System. out. println (s. equals (student);} catch (IOException e) {e. printStackTrace ();} catch (ClassNotFoundException e) {e. printStackTrace ();}}

Create the object Student and use the writeObject () method in the ObjectOutputStream class to output the object to the file.

Then, use the readObject () method in the ObjectinputStream class to deserialize and obtain the object.

 

      2.3.2 second write mode:

Implement the writeObject () and readObject () methods in the Student class:

  private void writeObject(ObjectOutputStream objectOutputStream) throws IOException {        objectOutputStream.defaultWriteObject();        objectOutputStream.writeUTF(id);    }    private void readObject(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {        objectInputStream.defaultReadObject();        id = objectInputStream.readUTF();    }

In this way, we can customize the variables we want to serialize, spread the input stream and output into the instance, and then serialize and deserialize the data.

  

      2.3.3 third write mode:

Student implementationExternalnalizable interface instead of Serializable Interface

The Externaliable interface is a subclass of Serializable and has the same functions as the Serializable interface:

public class Student implements Externalizable {    private static final long serialVersionUID = 3404072173323892464L;    private String name;    private transient String id;    private String age;    @Override    public String toString() {        return "Student{" +                "name='" + name + '\'' +                ", id='" + id + '\'' +                ", age='" + age + '\'' +                '}';    }    public String getAge() {        return age;    }    public void setAge(String age) {        this.age = age;    }    public Student(String name, String id) {        System.out.println("args Constructor");        this.name = name;        this.id = id;    }    public Student() {        System.out.println("none-arg Constructor");    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getId() {        return id;    }    public void setId(String id) {        this.id = id;    }    @Override    public void writeExternal(ObjectOutput out) throws IOException {        out.writeObject(name);        out.writeObject(id);    }    @Override    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {        name = (String) in.readObject();        id = (String) in .readObject();    }}

 

   By comparing with the second write method, we can find that their implementation principle is very similar,Externalnalizable InterfaceThe first serialization method is not supported. It can only implement Object serialization by implementing the writeExternal () and readExternal () methods in the interface.

 

 

3. serialization issues during the interview:

1. What is serialization and how to implement serialization

In java, Object serialization converts an object to a binary sequence, while deserialization converts a binary sequence to an object.

Java serialization can be implemented in multiple ways.

1. First, use the tool class ObjectInputStream and ObjectOutputStream.

2. Implement the Serializable interface:

There are two specific serialization methods:

2.1 directly use the writeObject () and readObject () methods in the ObjectOutputStream and ObjectInputStream classes

2.2 implement the writeObject () and readObject () methods in the serialized object, and pass in the ObjectOutputStream and ObjectInputStream objects to complete serialization.

3. Implement the Externalizable interface:

Only the writeExternal () and readExternal () methods in the interface can be implemented to serialize objects.


2. transient keyword? How do I serialize variables modified by the transient modifier?
        
Transient is used to block variables that we do not want to serialize. It is a variable that is ignored by objects during serialization and deserialization.
We can call the writeUTF () and readUTF () Methods of the output stream or input stream through the writeObject and readObject methods in the serialization method above.
You can also implement the writeExternal () and readExternal () methods by implementing the Externalizable interface, and then customize the sequence object.

     
3. How can we ensure the consistency between the serialized and deserialized objects? (If you have any objection, please confirm it)
       
After reading some materials, I found that the serialization and deserialization objects cannot be consistent, because during the deserialization process, is to create an object first,
Then, the object is deserialized by assigning values to the object. The problem arises. After a new object is created, the object reference and the original object do not point to the same target.
Therefore, we can only ensure that their data and version are consistent, and the object is not consistent.
 

  

    

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.