当前位置:网站首页>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;
边栏推荐
- [slam] orb-slam3 parsing - track () (3)
- STC8H开发(十二): I2C驱动AT24C08,AT24C32系列EEPROM存储
- 2、GPIO相关操作
- [matlab] - draw a five-star red flag
- Prime Protocol宣布在Moonbeam上的跨链互连应用程序
- Flask learning and project practice 8: introduction and use of cookies and sessions
- Overview of super-resolution reconstruction of remote sensing images
- BUAA喜鹊筑巢
- [meisai] meisai thesis reference template
- C mouse event and keyboard event of C (XXVIII)
猜你喜欢
Network security - Security Service Engineer - detailed summary of skill manual (it is recommended to learn and collect)
Cubemx transplantation punctual atom LCD display routine
Svg drag point crop image JS effect
Cf464e the classic problem [shortest path, chairman tree]
Canvas cut blocks game code
Blue Bridge Cup - day of week
mysql从一个连续时间段的表中读取缺少数据
No qualifying bean of type ‘......‘ available
In Net 6 CS more concise method
1、工程新建
随机推荐
Failure causes and optimization methods of LTE CSFB
[optimization model] Monte Carlo method of optimization calculation
C (thirty) C combobox listview TreeView
Factors affecting user perception
Schnuka: 3D vision detection application industry machine vision 3D detection
[001] [stm32] how to download STM32 original factory data
Crawler of explanation and application of agency theory
Scalpel like analysis of JVM -- this article takes you to peek into the secrets of JVM
有条件地 [JsonIgnore]
WPF effect Article 191 box selection listbox
Facebook等大廠超十億用戶數據遭泄露,早該關注DID了
SWC introduction
[American competition] mathematical terms
关于非虚函数的假派生
Containerization Foundation
Pointer for in-depth analysis (problem solution)
Edcircles: a real time circle detector with a false detection control translation
Prime Protocol宣布在Moonbeam上的跨链互连应用程序
SAP ALV cell level set color
After five years of testing in byte, I was ruthlessly dismissed in July, hoping to wake up my brother who was paddling