亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Java JavaBase Talk about serialization and deserialization in Java objects

Talk about serialization and deserialization in Java objects

Jul 03, 2020 am 10:03 AM
java object Deserialization Serialization

Talk about serialization and deserialization in Java objects

1. The concept of serialization and deserialization

Convert the object to The process of byte sequence is called serialization of an object.

The process of restoring a byte sequence into an object is called object deserialization.

The serialization of objects has two main uses:

1) Permanently save the object's byte sequence to the hard disk, usually in a file;

2) Transmit the byte sequence of the object over the network.

In many applications, certain objects need to be serialized so that they can leave the memory space and move to the physical hard disk for long-term storage. For example, the most common one is the Session object in the Web server. When 100,000 users access it concurrently, there may be 100,000 Session objects, which may be too much for the memory, so the Web container will serialize some sessions to the hard disk first, and so on. When you want to use it, restore the object saved in the hard disk to the memory.

When two processes are communicating remotely, they can send various types of data to each other. No matter what type of data it is, it is transmitted over the network in the form of a binary sequence. The sender needs to convert this Java object into a byte sequence before it can be transmitted over the network; the receiver needs to restore the byte sequence into a Java object.

2. Serialization API in JDK class library

java.io.ObjectOutputStream represents the object output stream, and its writeObject(Object obj ) method can serialize the obj object specified by the parameter and write the resulting byte sequence to a target output stream.
 java.io.ObjectInputStream represents an object input stream. Its readObject() method reads a sequence of bytes from a source input stream, deserializes them into an object, and returns it.
Only objects of classes that implement the Serializable and Externalizable interfaces can be serialized. Externalizable interface inherits from Serializable interface. Classes that implement the Externalizable interface completely control the serialization behavior by themselves, while classes that only implement the Serializable interface can Use the default serialization method.
 Object serialization includes the following steps:
 1) Create an object output stream, which can wrap a target output stream of other types, such as a file output stream;
 2) Through writeObject() of the object output stream Method writes object.

The steps for object deserialization are as follows:
1) Create an object input stream, which can wrap an other type of source input stream, such as a file input stream;
2) Pass the object input stream The readObject() method reads the object.

Object serialization and deserialization examples:

Define a Person class and implement the Serializable interface

import java.io.Serializable;

/**
 * <p>ClassName: Person<p>
 * <p>Description:測試對象序列化和反序列化<p>
 * @author xudp
 * @version 1.0 V
 * @createTime 2014-6-9 下午02:33:25
 */
public class Person implements Serializable {

    /**
     * 序列化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 age) {
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}

  Serializing and deserializing Person class objects

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: 測試對象的序列化和反序列<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 {
        SerializePerson();//序列化Person對象
        Person p = DeserializePerson();//反序列Perons對象
        System.out.println(MessageFormat.format("name={0},age={1},sex={2}",
                                                 p.getName(), p.getAge(), p.getSex()));
    }

    /**
     * MethodName: SerializePerson
     * Description: 序列化Person對象
     * @author xudp
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void SerializePerson() throws FileNotFoundException,
            IOException {
        Person person = new Person();
        person.setName("gacl");
        person.setAge(25);
        person.setSex("男");
        // ObjectOutputStream 對象輸出流,將Person對象存儲到E盤的Person.txt文件中,完成對Person對象的序列化操作
        ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(
                new File("E:/Person.txt")));
        oo.writeObject(person);
        System.out.println("Person對象序列化成功!");
        oo.close();
    }

    /**
     * MethodName: DeserializePerson
     * Description: 反序列Perons對象
     * @author xudp
     * @return
     * @throws 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("Person對象反序列化成功!");
        return person;
    }

}

The code running results are as follows:

Talk about serialization and deserialization in Java objects

After serializing Person successfully A Person.txt file is generated on the E drive, and the deserialized Person generates a Person object after reading the Person.txt of the E drive

3. The role of serialVersionUID

serialVersionUID: literally means the serialized version number. Every class that implements the Serializable interface has a static variable representing the serialized version identifier

private static final long serialVersionUID

If a class that implements the Serializable interface does not add serialVersionUID to the class, the following warning will appear

Talk about serialization and deserialization in Java objects

Click with the mouse A dialog box for generating serialVersionUID will pop up, as shown below:

Talk about serialization and deserialization in Java objects

There are two ways to generate serialVersionUID:

Use this The serialVersionUID generated by this method is 1L, for example:

private static final long serialVersionUID = 1L;

The serialVersionUID generated by is based on the class name, interface name, method and attribute, etc., for example:

private static final long serialVersionUID = 4603642343377807741L;

After adding it, the warning prompt will not appear, as shown below:

Talk about serialization and deserialization in Java objects

After so much, what is the serialVersionUID (serialized version number)? What's the use? Let's use the following example to illustrate the role of serialVersionUID. Look at the following code:

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.io.Serializable;

public class TestSerialversionUID {

    public static void main(String[] args) throws Exception {
        SerializeCustomer();// 序列化Customer對象
        Customer customer = DeserializeCustomer();// 反序列Customer對象
        System.out.println(customer);
    }

    /**
     * MethodName: SerializeCustomer
     * Description: 序列化Customer對象
     * @author xudp
     * @throws FileNotFoundException
     * @throws IOException
     */
    private static void SerializeCustomer() throws FileNotFoundException,
            IOException {
        Customer customer = new Customer("gacl",25);
        // ObjectOutputStream 對象輸出流
        ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(
                new File("E:/Customer.txt")));
        oo.writeObject(customer);
        System.out.println("Customer對象序列化成功!");
        oo.close();
    }

    /**
     * MethodName: DeserializeCustomer
     * Description: 反序列Customer對象
     * @author xudp
     * @return
     * @throws Exception
     * @throws IOException
     */
    private static Customer DeserializeCustomer() throws Exception, IOException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
                new File("E:/Customer.txt")));
        Customer customer = (Customer) ois.readObject();
        System.out.println("Customer對象反序列化成功!");
        return customer;
    }
}

/**
 * <p>ClassName: Customer<p>
 * <p>Description: Customer實現(xiàn)了Serializable接口,可以被序列化<p>
 * @author xudp
 * @version 1.0 V
 * @createTime 2014-6-9 下午04:20:17
 */
class Customer implements Serializable {
    //Customer類中沒有定義serialVersionUID
    private String name;
    private int age;

    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /*
     * @MethodName toString
     * @Description 重寫Object類的toString()方法
     * @author xudp
     * @return string
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "name=" + name + ", age=" + age;
    }
}

Running results:

Talk about serialization and deserialization in Java objectsTalk about serialization and deserialization in Java objects

序列化和反序列化都成功了。

下面我們修改一下Customer類,添加多一個sex屬性,如下:

class Customer implements Serializable {
    //Customer類中沒有定義serialVersionUID
    private String name;
    private int age;

    //新添加的sex屬性
    private String sex;

    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Customer(String name, int age,String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    /*
     * @MethodName toString
     * @Description 重寫Object類的toString()方法
     * @author xudp
     * @return string
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "name=" + name + ", age=" + age;
    }
}

然后執(zhí)行反序列操作,此時就會拋出如下的異常信息:

1 Exception in thread "main" java.io.InvalidClassException: Customer; 
2 local class incompatible: 
3 stream classdesc serialVersionUID = -88175599799432325, 
4 local class serialVersionUID = -5182532647273106745

意思就是說,文件流中的class和classpath中的class,也就是修改過后的class,不兼容了,處于安全機(jī)制考慮,程序拋出了錯誤,并且拒絕載入。那么如果我們真的有需求要在序列化后添加一個字段或者方法呢?應(yīng)該怎么辦?那就是自己去指定serialVersionUID。在TestSerialversionUID例子中,沒有指定Customer類的serialVersionUID的,那么java編譯器會自動給這個class進(jìn)行一個摘要算法,類似于指紋算法,只要這個文件 多一個空格,得到的UID就會截然不同的,可以保證在這么多類中,這個編號是唯一的。所以,添加了一個字段后,由于沒有顯指定 serialVersionUID,編譯器又為我們生成了一個UID,當(dāng)然和前面保存在文件中的那個不會一樣了,于是就出現(xiàn)了2個序列化版本號不一致的錯誤。因此,只要我們自己指定了serialVersionUID,就可以在序列化后,去添加一個字段,或者方法,而不會影響到后期的還原,還原后的對象照樣可以使用,而且還多了方法或者屬性可以用。

下面繼續(xù)修改Customer類,給Customer指定一個serialVersionUID,修改后的代碼如下:

class Customer implements Serializable {
    /**
     * Customer類中定義的serialVersionUID(序列化版本號)
     */
    private static final long serialVersionUID = -5182532647273106745L;
    private String name;
    private int age;

    //新添加的sex屬性
    //private String sex;

    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    /*public Customer(String name, int age,String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }*/

    /*
     * @MethodName toString
     * @Description 重寫Object類的toString()方法
     * @author xudp
     * @return string
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "name=" + name + ", age=" + age;
    }
}

重新執(zhí)行序列化操作,將Customer對象序列化到本地硬盤的Customer.txt文件存儲,然后修改Customer類,添加sex屬性,修改后的Customer類代碼如下:

class Customer implements Serializable {
    /**
     * Customer類中定義的serialVersionUID(序列化版本號)
     */
    private static final long serialVersionUID = -5182532647273106745L;
    private String name;
    private int age;

    //新添加的sex屬性
    private String sex;

    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Customer(String name, int age,String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    /*
     * @MethodName toString
     * @Description 重寫Object類的toString()方法
     * @author xudp
     * @return string
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "name=" + name + ", age=" + age;
    }
}

執(zhí)行反序列操作,這次就可以反序列成功了,如下所示:

Talk about serialization and deserialization in Java objects

四、serialVersionUID的取值

serialVersionUID的取值是Java運行時環(huán)境根據(jù)類的內(nèi)部細(xì)節(jié)自動生成的。如果對類的源代碼作了修改,再重新編譯,新生成的類文件的serialVersionUID的取值有可能也會發(fā)生變化。

類的serialVersionUID的默認(rèn)值完全依賴于Java編譯器的實現(xiàn),對于同一個類,用不同的Java編譯器編譯,有可能會導(dǎo)致不同的 serialVersionUID,也有可能相同。為了提高serialVersionUID的獨立性和確定性,強(qiáng)烈建議在一個可序列化類中顯示的定義serialVersionUID,為它賦予明確的值。

顯式地定義serialVersionUID有兩種用途:

1、 在某些場合,希望類的不同版本對序列化兼容,因此需要確保類的不同版本具有相同的serialVersionUID;

2、 在某些場合,不希望類的不同版本對序列化兼容,因此需要確保類的不同版本具有不同的serialVersionUID。

推薦學(xué)習(xí):Java視頻教程

The above is the detailed content of Talk about serialization and deserialization in Java objects. For more information, please follow other related articles on the PHP Chinese website!

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1488
72
What is the creation process of Java objects? What is the creation process of Java objects? Apr 11, 2024 pm 12:51 PM

Java object creation involves the following steps: Class loading: Loading the binary code of a class. Memory allocation: Allocate memory space for objects in heap memory. Instantiation: Create a new instance of an object in the allocated memory space. Initialization: Initialize the object's instance variables with default values. Constructor call: The appropriate constructor is called to initialize the remaining fields of the object.

PHP data processing skills: How to use the serialize and unserialize functions to implement data serialization and deserialization PHP data processing skills: How to use the serialize and unserialize functions to implement data serialization and deserialization Jul 29, 2023 am 10:49 AM

PHP data processing skills: How to use the serialize and unserialize functions to implement data serialization and deserialization Serialization and deserialization are one of the commonly used data processing skills in computer science. In PHP, we can use the serialize() and unserialize() functions to implement data serialization and deserialization operations. This article will give you a detailed introduction to how to use these two functions and provide relevant code examples. 1. What is serialization and deserialization in computer programming?

How to solve php deserialization failure How to solve php deserialization failure Oct 11, 2023 am 09:30 AM

Solution to PHP deserialization failure Check the serialized data. Check class definitions, check error logs, update PHP versions and apply security measures, etc. Detailed introduction: 1. Check the serialized data. First check whether the serialized data is valid and conforms to PHP's serialization specification. If the data is damaged or has an incorrect format, you can try to repair it or restore the correct data from backup; 2. Check Class definition, ensure that all classes used in serialized data exist and can be automatically loaded. If the class does not exist or is inaccessible, you can try to repair the class definition, etc.

In Java, how can we serialize a list of objects using flexjson? In Java, how can we serialize a list of objects using flexjson? Sep 05, 2023 pm 11:09 PM

Flexjson is a lightweight library for serializing and deserializing Java objects to and from JSON format. We can serialize a list of objects using the serialize() method of the JSONSerializer class. This method performs shallow serialization on the target instance. We need to pass a list of objects of list type as a parameter to the serialize() method. Syntax publicStringserialize(Objecttarget) example importflexjson.JSONSerializer;importjava.util.*;publicclassJsonSerial

How does the C++ function library perform serialization and deserialization? How does the C++ function library perform serialization and deserialization? Apr 18, 2024 am 10:06 AM

C++ Library Serialization and Deserialization Guide Serialization: Creating an output stream and converting it to an archive format. Serialize objects into archive. Deserialization: Creates an input stream and restores it from archive format. Deserialize objects from the archive. Practical example: Serialization: Creating an output stream. Create an archive object. Create and serialize objects into the archive. Deserialization: Create an input stream. Create an archive object. Create objects and deserialize them from the archive.

Understand the MyBatis execution process in one picture: the process of mapping SQL to Java objects Understand the MyBatis execution process in one picture: the process of mapping SQL to Java objects Feb 22, 2024 pm 04:33 PM

MyBatis is an excellent persistence layer framework that simplifies the process of interacting with databases in Java applications and greatly improves development efficiency. The core idea of ??the MyBatis framework is to map SQL statements to Java objects, and implement SQL mapping through XML configuration files or annotations, so that we can easily perform database operations. In MyBatis, the process of mapping SQL to Java objects can be simply divided into three steps: configuring the SQL mapping file, defining Java objects and

How to serialize the order of properties using Jackson library in Java? How to serialize the order of properties using Jackson library in Java? Aug 28, 2023 pm 12:45 PM

@JsonPropertyOrder is an annotation used at class level. It takes as an attribute a list of fields that defines the order in which the fields appear in the string generated by the JSON serialization of the object. Properties included in the annotation declaration can be serialized first (in the order they are defined), followed by any properties not included in the definition. Syntax public@interfaceJsonPropertyOrder Example importcom.fasterxml.jackson.core.*;importcom.fasterxml.jackson.databind.*;importcom.fasterxml.jac

How does Java serialization affect performance? How does Java serialization affect performance? Apr 16, 2024 pm 06:36 PM

The impact of serialization on Java performance: The serialization process relies on reflection, which will significantly affect performance. Serialization requires the creation of a byte stream to store object data, resulting in memory allocation and processing costs. Serializing large objects consumes a lot of memory and time. Serialized objects increase load when transmitted over the network.

See all articles