当前位置:网站首页>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;
边栏推荐
- mysql从一个连续时间段的表中读取缺少数据
- 【Qt5】Qt QWidget立刻出现并消失
- 2.2 fonctionnement stm32 GPIO
- Oracle ORA error message
- BUAA calculator (expression calculation - expression tree implementation)
- Take you to wechat applet development in 3 minutes
- 2.2 STM32 GPIO operation
- [matlab] - draw a five-star red flag
- Quick sort function in C language -- qsort
- How to standardize the deployment of automated testing?
猜你喜欢
Facebook等大廠超十億用戶數據遭泄露,早該關注DID了
Edcircles: a real time circle detector with a false detection control translation
2.13 weekly report
[001] [stm32] how to download STM32 original factory data
简易博客系统
登录mysql输入密码时报错,ERROR 1045 (28000): Access denied for user ‘root‘@‘localhost‘ (using password: NO/YES
SWC introduction
Cf464e the classic problem [shortest path, chairman tree]
Blue style mall website footer code
2.2 STM32 GPIO operation
随机推荐
RT-Thread--Lwip之FTP(2)
Blue Bridge Cup - day of week
Mapping between QoE and KQI
【可调延时网络】基于FPGA的可调延时网络系统verilog开发
2.1 rtthread pin设备详解
自动化测试怎么规范部署?
BUAA喜鹊筑巢
JVM的手术刀式剖析——一文带你窥探JVM的秘密
Svg drag point crop image JS effect
3分钟带你了解微信小程序开发
C (thirty) C combobox listview TreeView
Pandora IOT development board learning (HAL Library) - Experiment 9 PWM output experiment (learning notes)
Codeforces Global Round 19
Teach you to build your own simple BP neural network with pytoch (take iris data set as an example)
2、GPIO相关操作
如何修改表中的字段约束条件(类型,default, null等)
[prediction model] difference method model
1. New project
Mathematical modeling regression analysis relationship between variables
C form application of C (27)