Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Sample Analysis of Java Serialization and deserialization

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, the editor will bring you an example analysis of Java serialization and deserialization. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.

Serialization is the process of converting Java objects into byte sequences (byte streams). Then the deep copy is realized through the convection operation, and the serialized data is convenient for storage and transmission. Deserialization deserializes a byte sequence into a Java object.

Convenient storage: because objects are recycled, they can be persisted and stored on disk after serialization

Convenient transmission: byte sequences (in binary form) can be transmitted and propagated over the network.

It's best to set a SerialversionUID, because serialization and deserialization are compared to SerialversionUID, although one is generated by default without setting an interface, but you should know that the process of serializing objects is generally object-> serialization-> storage or transfer-> deserialization.

For example:

First create an entity class Student

Import lombok.Data;import java.io.Serializable;@Datapublic class Student implements Serializable {private Integer id; private String name; private String sex;} then create a test class SerializableTestimport serialization.entity.Student;import java.io.*;public class SerializableTest {public static void main (String [] args) throws Exception {serializeStudent (); Student student = deserializeStudent (); System.out.println ("name:" + student.getName ()) System.out.println ("sex:" + student.getSex ());} private static void serializeStudent () throws IOException {Student student = new Student (); student.setId (1); student.setName ("Zhang San"); student.setSex ("male"); ObjectOutputStream out = new ObjectOutputStream (new File ("F:/student.txt") Out.writeObject (student); System.out.println ("serialization successful"); out.close ();} private static Student deserializeStudent () throws Exception {ObjectInputStream in = new ObjectInputStream (new FileInputStream (new File ("F:/student.txt")); Student student = (Student) in.readObject (); System.out.println ("deserialization successful"); return student }} execution result: serialization successfully deserialized successfully name: Zhang San sex: male can also be successful if SerialversionUID is not specified at this time, but object-> serialization-> store or transfer-> deserialization, shall we modify the Student class before the deserialization operation?

At this time, let's modify the code, comment out the deserialization code and serialize it first.

Import serialization.entity.Student;import java.io.*;public class SerializableTest {public static void main (String [] args) throws Exception {serializeStudent (); / Student student = deserializeStudent (); / / System.out.println ("name:" + student.getName ()); / / System.out.println ("sex:" + student.getSex ());} private static void serializeStudent () throws IOException {Student student = new Student () Student.setId (1); student.setName ("Zhang San"); student.setSex ("male"); ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream (new File ("F:/student.txt")); out.writeObject (student); System.out.println ("serialization successful"); out.close () } / / private static Student deserializeStudent () throws Exception {/ / ObjectInputStream in = new ObjectInputStream (new FileInputStream (new File ("F:/student.txt"); / / Student student = (Student) in.readObject (); / / System.out.println ("deserialization succeeded"); / / return student;//}} run result: serialization succeeded

Modify the Student class

Import lombok.Data;import java.io.Serializable;@Datapublic class Student implements Serializable {private Integer id; private String name; private String sex; private String address;} comments out the serialization method and deserializes import serialization.entity.Student;import java.io.*;public class SerializableTest {public static void main (String [] args) throws Exception {/ / serializeStudent (); Student student = deserializeStudent () System.out.println ("name:" + student.getName ()); System.out.println ("sex:" + student.getSex ());} / / private static void serializeStudent () throws IOException {/ / Student student = new Student (); / / student.setId (1); / / student.setName ("Zhang San"); / / student.setSex ("male") / ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream (/ / new File ("F:/student.txt")); / / out.writeObject (student); / / System.out.println ("serialization successful"); / / out.close (); / /} private static Student deserializeStudent () throws Exception {ObjectInputStream in = new ObjectInputStream (new FileInputStream (new File ("F:/student.txt") Student student = (Student) in.readObject (); System.out.println ("deserialization succeeded"); return student;}} execution result: Exception in thread "main" java.io.InvalidClassException: serialization.entity.Student Local class incompatible: stream classdesc serialVersionUID = 3846952599709361171 Local class serialVersionUID =-4606152942663467236 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 serialization.demo.SerializableTest.deserializeStudent (SerializableTest.java:30) at serialization.demo.SerializableTest.main (SerializableTest.java:10) Process finished with exit code 1 can see that the SerialversionUID of the two execution does not match. Causes a java.io.InvalidClassException exception to be generated, so no exception is reported as long as SerialversionUID is specified. / / specify that serialVersionUID is written correctly private static final long serialVersionUID = 3846952599709361L true / if you don't know SerialversionUID, you can get Object obj = Student.class.newInstance () through reflection; Field field = Student.class.getDeclaredField ("serialVersionUID"); field.setAccessible (true); System.out.println (field.getLong (obj))

The last thing to know is the difference between a byte stream and a character stream.

Byte stream: during transmission, the most basic unit of data transmission is the stream of bytes.

Character stream: in the process of transmission, the most basic unit of data transmission is the stream of characters.

It may be a bit confusing to say that bytes are actually the eight basic types of Byte (bit) units of Java, while the characters are usually'A','B','$','&', etc., and the byte size depends on your encoding (environment), as follows:

In ASCII code, an English letter (regardless of case) is one byte, and a Chinese character is two bytes.

In UTF-8 coding, an English word is one byte and a Chinese word is three bytes.

In Unicode coding, one English is one byte and one Chinese is two bytes.

Symbol: English punctuation is one byte and Chinese punctuation is two bytes. For example, a full stop in English. Occupies the size of 1 byte, Chinese full stop.

The size of 2 bytes. In UTF-16 coding, the storage of an English alphabet character or a Chinese character requires 2 bytes (some Chinese characters in the Unicode extension need 4 bytes).

In UTF-32 encoding, it takes 4 bytes to store any character in the world.

The above is the analysis of Java serialization and deserialization examples shared by Xiaobian. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report