Java object serialization and deserialization, java object serialization
1. Concepts of serialization and deserialization
The process of converting an object into a byte sequence is called object serialization..
The process of restoring a byte sequence to an object is called object deserialization..
Object serialization has two main purposes:
1) the object's byte sequence is permanently stored on the hard disk, usually stored in a file;
2) transmits the object's byte sequence over the network.
In many applications, some objects need to be serialized so that they can leave the memory space and stay on the physical hard disk for long-term storage. For example, the most common is the Session object in the Web server. When 0.1 million users access the Session object concurrently, 0.1 million Session objects may appear, and the memory may not be enough, therefore, the Web Container first serializes some seesion to the hard disk, and then restores the objects stored in the hard disk to the memory.
When two processes perform remote communication, they can send different types of data to each other. Regardless of the type of data, it is transmitted on the network in the form of binary sequence. The sender needs to convert the Java object into a byte sequence before it can be transmitted over the network. The receiver needs to restore the byte sequence to a Java object.
II,
Serialization API in JDK class library
Java. io. ObjectOutputStream represents the Object output stream. Its writeObject (Object obj) method can serialize the obj Object specified by the parameter and write the obtained byte sequence to a target output stream.
Java. io. ObjectInputStream indicates the object input stream. Its readObject () method reads byte sequences 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. The Externalizable interface inherits from the Serializable interface. classes that implement the Externalizable interface completely control the serialization behavior. classes that only implement the Serializable interface can adopt the default serialization method.
Object serialization includes the following steps:
1) create an object output stream, which can wrap a target output stream of another type, such as a file output stream;
2) write an object using the writeObject () method of the object output stream.
The steps for object deserialization are as follows:
1) create an object input stream, which can wrap a source input stream of another type, such as a file input stream;
2) read the object through the readObject () method of the object input stream.
Example of Object serialization and deserialization:
Define a Person class to implement the Serializable Interface
1 import java. io. serializable; 2 3/** 4 * <p> ClassName: Person <p> 5 * <p> Description: test Object serialization and deserialization <p> 6 * @ author xudp 7 * @ version 1.0 V 8 * @ createTime 02:33:25 9 */10 public class Person implements Serializable {11 12/ ** 13 * serialize ID14 */15 private static final long serialVersionUID =-5809782578272943999L; 16 private int age; 17 private String name; 18 private String sex; 19 20 public int getAge () {21 return age; 22} 23 24 public String getName () {25 return name; 26} 27 28 public String getSex () {29 return sex; 30} 31 32 public void setAge (int age) {33 this. age = age; 34} 35 36 public void setName (String name) {37 this. name = name; 38} 39 40 public void setSex (String sex) {41 this. sex = sex; 42} 43}
Serialize and deserialize Person objects
1 import java. io. file; 2 import java. io. fileInputStream; 3 import java. io. fileNotFoundException; 4 import java. io. fileOutputStream; 5 import java. io. IOException; 6 import java. io. objectInputStream; 7 import java. io. objectOutputStream; 8 import java. text. messageFormat; 9 10/** 11 * <p> ClassName: TestObjSerializeAndDeserialize <p> 12 * <p> Description: serialization and deserialization of test objects <p> 13 * @ author xudp14 * @ version 1.0 V 15 * @ createTime */17 public class TestObjSerializeAndDeserialize {18 19 public static void main (String [] args) throws Exception {20 SerializePerson (); // serialize Person object 21 Person p = DeserializePerson (); // Reverse Sequence Perons object 22 System. out. println (MessageFormat. format ("name = {0}, age = {1}, sex = {2}", 23 p. getName (), p. getAge (), p. getSex (); 24} 25 26/** 27 * MethodName: SerializePerson 28 * Descr Iption: serialize the Person object 29 * @ author xudp30 * @ throws FileNotFoundException31 * @ throws IOException32 */33 private static void SerializePerson () throws FileNotFoundException, 34 IOException {35 Person person = new Person (); 36 person. setName ("gacl"); 37 person. setAge (25); 38 person. setSex ("male"); 39 // ObjectOutputStream: stores the personas in the person.txt file of the edisk, and completes the serialization of the Person Object. 40 ObjectOutputStream oo = new Object OutputStream (new FileOutputStream (41 new File ("E:/Person.txt"); 42 oo. writeObject (person); 43 System. out. println ("Person object serialized successfully! "); 44 oo. close (); 45} 46 47/** 48 * MethodName: DeserializePerson 49 * Description: anti-sequential Perons object 50 * @ author xudp51 * @ return52 * @ throws Exception53 * @ throws IOException54 */55 private static Person DeserializePerson () throws Exception, IOException {56 ObjectInputStream ois = new ObjectInputStream (new FileInputStream (57 new File ("E:/Person.txt"); 58 Person person Person = (Person) ois. readObject (); 59 Sys Tem. out. println ("the Person object is deserialized successfully! "); 60 return person; 61} 62 63}
The code execution result is as follows:
After successful personas, A person.txt file is generated on the edisk, while the reverse sequence personas generate a Person object after reading the person.txt file of the edisk.
Iii. Functions of serialVersionUID
SerialVersionUID: The serialized version number. All classes that implement the Serializable interface have a static variable that represents the serialized version identifier.
1 private static final long serialVersionUID
If serialVersionUID is not added to the class that implements the Serializable interface, the following warning will appear:
Click the mouse to display the generate serialVersionUID dialog box, as shown in:
SerialVersionUID can be generated in two ways:
The serialVersionUID generated in this way is 1L, for example:
1 private static final long serialVersionUID = 1L;
SerialVersionUID generated in this way is generated based on the class name, Interface Name, method, and attribute, for example:
1 private static final long serialVersionUID = 4603642343377807741L;
The warning prompt will not appear after you add it, as shown below:
If so, what is the purpose of serialVersionUID (serialization version number)? Let's use the following example to illustrate the role of serialVersionUID. Let's look at the following code:
1 import java. io. file; 2 import java. io. fileInputStream; 3 import java. io. fileNotFoundException; 4 import java. io. fileOutputStream; 5 import java. io. IOException; 6 import java. io. objectInputStream; 7 import java. io. objectOutputStream; 8 import java. io. serializable; 9 10 public class TestSerialversionUID {11 12 public static void main (String [] args) throws Exception {13 SerializeCustomer (); // serializcus Tomer object 14 Customer customer = DeserializeCustomer (); // Reverse Sequence Customer object 15 System. out. println (customer); 16} 17 18/** 19 * MethodName: SerializeCustomer 20 * Description: serialize the Customer object 21 * @ author xudp22 * @ throws FileNotFoundException23 * @ throws IOException24 */25 private static void SerializeCustomer () throws FileNotFoundException, 26 IOException {27 Customer customer = new Customer ("gacl", 25); 28 // ObjectOutputStream object output stream 29 ObjectOutputStream oo = new ObjectOutputStream (new FileOutputStream (30 new File ("E:/Customer.txt"); 31 oo. writeObject (customer); 32 System. out. println ("the Customer object is serialized successfully! "); 33 oo. close (); 34} 35 36/** 37 * MethodName: DeserializeCustomer 38 * Description: reverse Sequence Customer object 39 * @ author xudp40 * @ return41 * @ throws Exception42 * @ throws IOException43 */44 private static Customer DeserializeCustomer () throws Exception, IOException {45 ObjectInputStream ois = new ObjectInputStream (new FileInputStream (46 new File ("E:/Customer.txt"); 47 Customer customer Customer = (Customer) ois. rea DObject (); 48 System. out. println ("the Customer object is deserialized successfully! "); 49 return customer; 50} 51} 52 53/** 54 * <p> ClassName: Customer <p> 55 * <p> Description: Customer implements the Serializable interface, can be serialized <p> 56 * @ author xudp57 * @ version 1.0 V58 * @ createTime: 20: 1759 */60 class Customer implements Serializable {61 // The serialVersionUID62 private String name; 63 private int age is not defined in the Customer class; 64 65 public Customer (String name, int age) {66 this. name = name; 67 this. age = age; 68} 69 70/* 71 * @ MethodName toString72 * @ Description override the toString () method of the Object class 73 * @ author xudp74 * @ return string75 * @ see java. lang. object # toString () 76 */77 @ Override78 public String toString () {79 return "name =" + name + ", age =" + age; 80} 81}
Running result:
Both serialization and deserialization are successful.
Next we will modify the Customer class and add an additional sex attribute, as shown below:
1 class Customer implements Serializable {2 // The serialVersionUID 3 private String name; 4 private int age; 5 6 // the newly added sex attribute 7 is not defined in the Customer classPrivate String sex;8 9 public Customer (String name, int age) {10 this. name = name; 11 this. age = age; 12} 13 14 public Customer (String name, int age, String sex) {15 this. name = name; 16 this. age = age; 17 this. sex = sex; 18} 19 20/* 21 * @ MethodName toString22 * @ Description rewrite the toString () method of the Object Class 23 * @ author xudp24 * @ return string25 * @ see java. lang. object # toString () 26 */27 @ Override28 public String toString () {29 return "name =" + name + ", age =" + age; 30} 31}
Then execute the anti-sequence operation, and the following exception information will be thrown:
1 Exception in thread "main" java.io.InvalidClassException: Customer; 2 local class incompatible: 3 stream classdesc serialVersionUID = -88175599799432325, 4 local class serialVersionUID = -5182532647273106745
This means that the class in the file stream is incompatible with the class in the classpath, that is, the modified class. In consideration of the security mechanism, the program throws an error and rejects loading. So what if we really need to add a field or method after serialization? What should I do? That is, specify the serialVersionUID. In the TestSerialversionUID example, if the serialVersionUID of the Customer class is not specified, the java compiler automatically implements a digest algorithm for the class, similar to the fingerprint algorithm, as long as there is one more space in the file, the obtained UID will be completely different. It can be ensured that this number is unique in so many categories. Therefore, after a field is added, because the serialVersionUID is not explicitly specified, the compiler generates a UID for us. Of course, this is not the same as the one saved in the file, therefore, two serialization version numbers are inconsistent. Therefore, as long as we specify the serialVersionUID, we can add a field or method after serialization without affecting the subsequent restoration. The restored object can still be used, besides, methods or attributes can be used.
Next, modify the Customer class and specify a serialVersionUID for the Customer. The modified code is as follows:
1 class Customer implements Serializable {2/*** 3 * serialVersionUID (serialization version) defined in the Customer class 4 */5Private static final long serialVersionUID =-5182532647273106745L;6 private String name; 7 private int age; 8 9 // newly added sex attribute 10 // private String sex; 11 12 public Customer (String name, int age) {13 this. name = name; 14 this. age = age; 15} 16 17/* public Customer (String name, int age, String sex) {18 this. name = name; 19 this. age = age; 20 this. sex = sex; 21} */22 23/* 24 * @ MethodName toString25 * @ Description override the toString () of the Object class () method 26 * @ author xudp2 * @ return string28 * @ see java. lang. object # toString () 29 */30 @ Override31 public String toString () {32 return "name =" + name + ", age =" + age; 33} 34}
Re-execute the sequential operation, convert the merobject sequence to the customer.txt file storage on a hard disk, modify the Customer class, and add the sex attribute. The modified Customer class code is as follows:
1 class Customer implements Serializable {2/*** 3 * serialVersionUID (serialization version) defined in the Customer class 4 */5Private static final long serialVersionUID =-5182532647273106745L;6 private String name; 7 private int age; 8 9 // the newly added sex attribute 10Private String sex;11 12 public Customer (String name, int age) {13 this. name = name; 14 this. age = age; 15} 16 17 public Customer (String name, int age, String sex) {18 this. name = name; 19 this. age = age; 20 this. sex = sex; 21} 22 23/* 24 * @ MethodName toString25 * @ Description rewrite the toString () method of the Object Class 26 * @ author xudp2 * @ return string28 * @ see java. lang. object # toString () 29 */30 @ Override31 public String toString () {32 return "name =" + name + ", age =" + age; 33} 34}
Perform the reverse sequence operation. This time, the reverse sequence is successful, as shown below:
Iv. Value of serialVersionUID
The value of serialVersionUID is automatically generated in the Java Runtime Environment according to the internal details of the class. If the source code of the class is modified and re-compiled, the serialVersionUID value of the newly generated class file may also change.
The default value of serialVersionUID of the class is completely dependent on the implementation of the Java compiler. For the same class, compiling with different Java compilers may lead to different serialVersionUID and may also be the same.To improve the independence and certainty of serialVersionUID, we strongly recommend that you define serialVersionUID in a serializable class and assign it a clear value..
SerialVersionUID can be explicitly defined for two purposes:
1. In some cases, different versions of the class are expected to be compatible with serialization. Therefore, ensure that different versions of the class have the same serialVersionUID;
2. In some cases, different versions of the class are not required to be compatible with serialization. Therefore, make sure that different versions of the class have different serialVersionUID.