当前位置:网站首页>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;
边栏推荐
- C (thirty) C combobox listview TreeView
- Flask learning and project practice 9: WTF form verification
- 3.1 rtthread 串口设备(V1)详解
- KS003基于JSP和Servlet实现的商城系统
- C language -- structs, unions, enumerations, and custom types
- 1.16 - check code
- Cubemx 移植正点原子LCD显示例程
- UDP reliable transport protocol (quic)
- WPF效果第一百九十一篇之框选ListBox
- 登录mysql输入密码时报错,ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: NO/YES
猜你喜欢
[Massey] Massey font format and typesetting requirements
Svg drag point crop image JS effect
Blue Bridge Cup - Castle formula
Overview of super-resolution reconstruction of remote sensing images
mysql关于自增长增长问题
MySQL reads missing data from a table in a continuous period of time
How to standardize the deployment of automated testing?
Facebook等大厂超十亿用户数据遭泄露,早该关注DID了
[analysis of variance] single factor analysis and multi factor analysis
【可调延时网络】基于FPGA的可调延时网络系统verilog开发
随机推荐
Blue Bridge Cup - day of week
[practical exercise] face location model based on skin color
【PSO】基于PSO粒子群优化的物料点货物运输成本最低值计算matlab仿真,包括运输费用、代理人转换费用、运输方式转化费用和时间惩罚费用
3分钟带你了解微信小程序开发
RT thread -- FTP of LwIP (2)
KS003基于JSP和Servlet实现的商城系统
How do we make money in agriculture, rural areas and farmers? 100% for reference
Multi project programming minimalist use case
2.2 fonctionnement stm32 GPIO
mysql从一个连续时间段的表中读取缺少数据
Remote Sensing Image Super-resolution and Object Detection: Benchmark and State of the Art
User experience index system
How to standardize the deployment of automated testing?
[optimization model] Monte Carlo method of optimization calculation
LTE CSFB test analysis
关于非虚函数的假派生
C#(三十一)之自定义事件
潘多拉 IOT 开发板学习(HAL 库)—— 实验9 PWM输出实验(学习笔记)
WPF effect Article 191 box selection listbox
【FPGA教程案例11】基于vivado核的除法器设计与实现