当前位置:网站首页>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)
serialVersionUID: 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;
边栏推荐
- The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
- Maxay paper latex template description
- Codeforces Global Round 19
- 简易博客系统
- Quick sort function in C language -- qsort
- Failure causes and optimization methods of LTE CSFB
- 3.2 rtthread 串口设备(V2)详解
- C (XXIX) C listbox CheckedListBox Imagelist
- WPF effect Article 191 box selection listbox
- 3.1 detailed explanation of rtthread serial port device (V1)
猜你喜欢
Suggestions for new engineer team members
Microkernel structure understanding
KS003基于JSP和Servlet实现的商城系统
Factors affecting user perception
自动化测试怎么规范部署?
Cubemx transplantation punctual atom LCD display routine
BUAA magpie nesting
Error 1045 (28000): access denied for user 'root' @ 'localhost' (using password: no/yes
Containerization Foundation
Teach you to build your own simple BP neural network with pytoch (take iris data set as an example)
随机推荐
C#(二十七)之C#窗体应用
[American competition] mathematical terms
Quick sort function in C language -- qsort
[optimization model] Monte Carlo method of optimization calculation
Schnuka: 3D vision detection application industry machine vision 3D detection
Custom event of C (31)
WPF效果第一百九十一篇之框选ListBox
关于非虚函数的假派生
C#(三十一)之自定义事件
施努卡:视觉定位系统 视觉定位系统的工作原理
Prime Protocol宣布在Moonbeam上的跨链互连应用程序
[slam] lidar camera external parameter calibration (Hong Kong University marslab) does not need a QR code calibration board
判断当天是当月的第几周
【FPGA教程案例12】基于vivado核的复数乘法器设计与实现
BUAA calculator (expression calculation - expression tree implementation)
2. GPIO related operations
Do you know cookies, sessions, tokens?
[practice] mathematics in lottery
在字节做测试5年,7月无情被辞,想给划水的兄弟提个醒
Codeforces Global Round 19