当前位置:网站首页>Detailed explanation of serialization and deserialization

Detailed explanation of serialization and deserialization

2022-07-06 03:51:00 Passerby Chen

1. Why  Java serialize (Serialization)?

Java Provides a object Serialization and Deserialization The mechanism of . Serialization is a mechanism for processing object streams , The so-called object flow is to flow the content of the object .

The serialized stream is called Serialization flow Persistent object ); The deserialized stream is called Deserialize stream Refactoring objects ).

Can fluidize the object Conduct read Write operation , The fluidized object can also be Transmission between Networks .

In short , object Serialization is the process of transforming the state of an object into a format that can be maintained or transmitted .

Serialization is to solve the problem of reading and writing to the object stream .

2. How to achieve Java serialize (Serialization)?

take Need to be want By order Column turn Of class real present Serializable Pick up mouth , The Pick up mouth no Yes Need to be want real present Of Fang Law , implements Serializable It's just To mark that the object is serializable , Then use an output stream ( Such as :FileOutputStream) To construct the One ObjectOutputStream( Object flow ) object , next , Use ObjectOutputStream Object's writeObject(Object obj) Method You can set the parameter to obj Object write out ( Save its status ), To restore, use input stream .

3.Java In serialization , What if some fields don't want to be serialized ?

         For variables that do not want to be serialized , Use transient Keyword modification .

When the object is serialized , Prevent serialization of variables in instances decorated with this keyword .

When the object is deserialized , By transient Decorated variable values are not persisted and restored .

transient Only variables can be decorated , Cannot modify classes and methods .

4. serialize and Deserialization effect

         serialize : Mainly used for network transmission , Data persistence , Serialization in general is also called encoding (Encode).

         Deserialization : It is mainly used to read the byte array from the network or disk and restore it to the original object , Generally, deserialization is also called decoding (Decode).

serialize and Deserialization

        1. Data persistence : In short , It is the time to store data in disk files , You need to serialize the object and save it to disk .

        2. Network transmission : When the same object needs to be transmitted in a distributed system , We use serialization and deserialization . Serialize and transfer the transferred objects to another system , Another system reads the byte sequence by converting it into an object

serialize , It means that Java Object to byte sequence ( Persistent object

java.io.ObjectOutputStream Class inheritance OutputStream,

Is a byte output stream , It can be used to write byte data , And you can write objects .

Considerations for serialization :
    1 The class of the serialized object must be implemented Serializable Interface ( Tag interface )
    2 All attributes of the serialized object should also be serializable
    3 If the properties of other serialized objects do not want to be serialized , Then this attribute needs to use transient Keyword modification , Indicates transient

public class Person implements Serializable {
    static final long serialVersionUID=21L;// Serialized version number 

    String name;
    int age;

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

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
// serialize 
public class Test01 {
    public static void main(String[] args) throws Exception{
        // 1. establish Person object 
        Person p = new Person(" Zhang San ",18);

        // 2. Create a serialized stream object , Associated destination file path 
        FileOutputStream fos = new FileOutputStream("day01\\aa\\a.txt");
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        // 3. Serializing objects 
        oos.writeObject(p);

        // 4. Closed flow , Release resources 
        oos.close();
    }
}

Deserialization , It refers to restoring the byte sequence to Java Object procedure ( Rebuild objects

java.io.ObjectInputStream Class inheritance InputStream,

Is a byte input stream , It can be used to read byte data , And you can read objects .

Considerations for deserialization :
    1 If you can't find it class file , Deserialization will fail , Throw a classNotFoundException abnormal incompatible
    2. If you can find this kind of class file , But after serialization, the class is modified , Will cause deserialization failure , Throw a InvalidClassException abnormal


solve InvalidClassException Deserialization method of exception :

         Increase the serialization version number :static final long serialVersionUID=21L

// Deserialization 
public class Test02 {
    public static void main(String[] args) throws Exception{
        // 1. Create deserialization stream object , Associated data source file path 
        FileInputStream fis = new FileInputStream("day01\\aa\\a.txt");
        ObjectInputStream ois = new ObjectInputStream(fis);

        // 2. Refactoring objects 
        Object obj = ois.readObject();

        // 3. Closed flow , Release resources 
        ois.close();

        // 4. Print object 
        System.out.println(obj.toString());
    }
}

Attention to serialization and deserialization :

Declare as static and transient Data of type cannot be serialized , Deserialization requires a parameterless constructor .

stay Java Classes that can be serialized in must first implement Serializable Interface , The interface does not have any abstract methods, but only acts as a marker .

Json/xml Data transfer

In data transmission ( Also known as network transmission ) front , First, through the sequence of the tool class Java Object serialization to Json/xml file .

In data transmission ( Also known as network transmission ) after , then Json/xml The file is deserialized to an object in the corresponding language .

Serialized version number (serialVersionUID)

s​e​r​i​a​l​V​e​r​s​i​o​n​U​I​D​:​ ​ word ​ Noodles ​ It means ​ thinking ​ On ​ yes ​ order ​ Column ​ turn ​ Of ​ edition ​ Ben ​ Number ​, All realized Serializable Each class of the interface has a static variable that represents the serialized version identifier .

Serialized version number (serialVersionUID) The role of

         When it comes to Serializable Class ( Serial version number is not defined ) After serialization, it was modified , An error will be reported when deserializing the instance object of this class , Because the serialized version number of this object does not correspond to the previous one after the class is modified ( Security mechanism ).

solve InvalidClassException Deserialization method of exception ( terms of settlement : Increase the serialization version number ):

         Specify a serialization version number when defining this class , In this way, the compiler will not automatically set the version number .

//serialVersionUID =  It can be for “ Any number ”+L, But don't repeat 
private static final long serialVersionUID = 1L;

原网站

版权声明
本文为[Passerby Chen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202132302117481.html