Senior Java - serialization (Serialization)

background

       In Java, you can create objects in a variety of ways, and as long as these objects are not being recovered with these objects can be reused. However, creating out of these objects are stored in the JVM heap (stack) memory only when JVM is running, these objects only exist once the JVM is stopped, these objects disappeared.

       If you need these objects persistent storage or transmission, and when you need to re-read the object out, Java serialization can help achieve.

concept

Serialization concept   

       Converting an object into a sequence of bytes is called serialized objects . The data byte sequence that contains the object, the type of information about an object stored in an object data types. File and writes the byte sequence (which may be a byte or XML format), it can be stored and transmitted .

Deserialization concepts

       Sequence of bytes written to the file to read out the recovery process for the object is called object deserialization . In other words, the type of information objects, data types and object data object can be used to create new objects in memory.

Serialization Features

       The whole process is a Java Virtual Machine (JVM) independent, that is, on a platform serialized object can deserialize the object on a completely different platform.

Serialization usage scenarios

1. Object network transmission For example: in a micro system service call or when providing an interface to a third party, using rpc call, the object will typically be converted into a sequence of bytes, it can be transmitted on the network; recipient then need to take a sequence of bytes into java object .
2. Save the object to a file For example: hibernate in the secondary cache: The query from a database object serialization dump the hard disk, the next time read from the first memory to find whether there is the object, if not going secondary cache (hard disk) to find. Reduce the number of database queries to improve performance.
...... ......

Serialization Prerequisites

       A class object you want to serialize successfully, the following two conditions need to be met:

  • The class must implement java.io.Serializable

        If a class does not implement the serialization interface, occurs java.io.NotSerializableException exception.

  • All properties of the class must be serializable. If a property is not serializable, the property must be marked transient (keyword Transient , save JVM the default value of the original value ignores the transient variables and variables into a file. Therefore, transient means not Serialization).

         If you try to serialize a serialized object can not be given, as follows:

 

use

    ObjectOutputStream Java IO package provides classes for a sequence of functions implemented in the class; ObjectInputStream class provides a deserialization implementation class. As follows:

The definition of student class ( note that at this time not to add serialVersionUID )

public class Account implements Serializable{
    private String username;
    private String password;
	
    public Student() {
    }
    public Student(String username, String password) {
        super();
        this.username = username;
        this.password = password;
    }
	@Override
    public String toString() {
        return "Account [username=" + username + ", password=" + password + "]";
    }
}

Serialization

public class SerializeTest {
    public static void main(String[] args) {
        Account account = new Account("Tom", "123");
		
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("account.ser");
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(student);
            objectOutputStream.close();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Deserialization

public class DeserializeTest {
    public static void main(String[] args) {
        Account account = null;
        try {
            FileInputStream fileInputStream = new FileInputStream("account.ser");
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
            account = (Account) objectInputStream.readObject();
            objectInputStream.close();
            fileInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }catch(ClassNotFoundException c){
            System.out.println("Account class not found");
            c.printStackTrace();
            return;
        }
        System.out.println(account);
    }
}
运行结果为:
Account [name=Tom, password=123]

 

transient keyword

         transient (short-term, transparent) key role is the sequence of the control variables, if the properties are not serialized , and then add the keyword before the variable declaration indicates that the property is short, the JVM will ignore transient modified variable value and the default value of the original variable type (e.g., int type is 0, the object type is null) saved to a file, so as not to be written to the file.

       As will be above the password field declared transient, as follows:

private transient String password;

       After deserialization results:

Account [name=Tom, password = null]

       

serialVersionUID

       In the above case, Account class has not added serialVersionUID (version number). If the sequence of the Account class, give the Account class to add a new field as follows:

public class Account implements Serializable{
	private String username;
	private transient String password;
	private double balance;  //为Account类添加新的字段
    
    ......
}

         Now then serialized, it will be reported java.io.InvalidClassException exception:

java.io.InvalidClassException: day13.Account; local class incompatible: stream classdesc serialVersionUID = 4186211771023085883, local class serialVersionUID = -3783640273171219810
	at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:699)
	at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1885)
	at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1751)
	at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2042)
	at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
	at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
	at day13.DeserializeTest.main(DeserializeTest.java:19)

         This is because the Account class changed, that is, after the modified class, are not compatible. In security considerations, the program throws an error and refuse to load. As can be seen from the exception information, it is determined whether or not modified according to the class serialVersionUID value.

         Note: figure, there are two serialVersionUID, not as if this is due to declare serialVersionUID property does not appear, then the java compiler automatically generates a serialVersionUID ( should be calculated according to the summary of properties and methods, in addition to the method body changes in content, serialVersionUID value will not change the outside, other changes will lead to a default serialVersionUID change, so there are two different serialVersionUID ).

         So, we need to display a statement serialVersionUID, so unique when it serialVersionUID definitions need to be serialized class. The version number of an agreement on de-serialization is successful, or an error occurs.

        So, in the above Account class need to add a serialVersionUID, so add the new field, the error will not. As follows:

public class Account implements Serializable{
    private static final long serialVersionUID = 1L;
    
    ......
}

          

 

 

reference:

https://www.jianshu.com/p/af2f0a4b03b5

https://www.runoob.com

 

 

Published 131 original articles · won praise 39 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_35507234/article/details/97154082