Home 类库下载 java类库 Java serialization and deserialization

Java serialization and deserialization

Oct 29, 2016 am 10:56 AM
java

1. What is serialization? Why serialize?

  Java serialization refers to the process of converting objects into byte sequences, while deserialization is the process of converting only byte sequences into target objects.

  We all know that when accessing a browser, the text, pictures, audio, video, etc. we see are transmitted through binary sequences. So if we need to transmit Java objects, is it also possible? Should the object be serialized first? The answer is yes, we need to serialize the Java object first, and then transmit it through the network and IO. When it reaches the destination, deserialize it to get the object we want, and finally complete the communication.

2. How to implement serialization

 2.1. Use the key classes ObjectOutputStream and ObjectInputStream in JDK

  In the ObjectOutputStream class: write the object in binary format by using the writeObject(Object object) method.

  In the ObjectInputStream class: By using the readObject() method, the binary stream is read from the input stream and converted into an object.

  2.2. The target object needs to implement the Serializable interface first

  

We 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;
    }

}
Copy after login

                                   over over from the code. The Student class implements the Serializable interface and generates a version number:

private static final long serialVersionUID = 3404072173323892464L;
Copy after login

   First:

1. The function of the Serializable interface is only to identify that our class needs to be serialized, and the Serializable interface does not provide any methods.

   2. serialVersionUid The serialization version number is used to distinguish the version of the class we write and to determine whether the version of the class is consistent during deserialization. If it is inconsistent, a version inconsistency exception will occur.

   3. The transient keyword is mainly used to ignore variables that we do not want to serialize

  2.3. Serialize or deserialize objects

   2.3.1 The first writing method:

public static  void main(String[] args){
        File file = new File("D:/test.txt");
        Student student = new Student("孙悟空","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();
        }
    }
Copy after login

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

     Then deserialize through the readObject() method in the ObjectinputStream class to obtain the object.

    2.3.2 The second writing method:

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();
    }
Copy after login

   Through this method of serialization, we can customize the serialization we want Variables, the input stream and output stream are passed into the line instance, and then serialized and deserialized.

 

    2.3.3 The third writing method:

Student implements the Externalnalizable interface but does not implement the 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();
    }

}
Copy after login

  Through the previous Comparing the second writing method, we can find that their implementation principles are very similar, but implementing the Externalnalizable interface does not support the first serialization method. It can only implement writeExternal() and readExternal() in the interface. Method implements serialization of objects.

3. Questions about serialization in interviews:

1. What is serialization and how to implement serialization

The serialization of objects in Java is to convert the object into a binary sequence, and deserialization is Convert a binary sequence into an object

   There are many ways to implement serialization in Java

  1. First, you need to use the two IO classes ObjectInputStream and ObjectOutputStream of the tool class

                                     duct ObjectInputStream Specific serialization method :

                                               ulous in in in ining in in on in the writeObject() and readObject() methods in the ObjectOutputStream and ObjectInputStream classes

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

    3. Implement the Externalizable interface:

      Object serialization can only be achieved by implementing the writeExternal() and readExternal() methods in the interface


   2. Transient keyword? How to serialize variables modified with transient modifier?
    The function of transient is to shield variables that we do not want to serialize. The object ignores the variable during the serialization and deserialization process.
    We can implement the writeObject and readObject methods in the above serialization method, and call the writeUTF() and readUTF() methods of the output stream or input stream in the method.
   Or by implementing the Externalizable interface, implement the writeExternal() and readExternal() methods, and then customize the sequence object.

      3. How to ensure that the objects after serialization and deserialization are consistent? (Please correct me if you have any objections)
    After consulting some information on this issue, I found that there is no guarantee that the objects after serialization and deserialization are consistent, because during the deserialization process, we first create a Object,
     
     Therefore, we can only ensure that their data and versions are consistent, but we cannot guarantee that the objects are consistent.


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles