Serialization and deserialization
- Serialization: The process of converting an object into a sequence of bytes is called object serialization.
- Deserialization: The process of restoring a sequence of bytes to an object is called deserialization of an object.
When is serialization and deserialization needed
When we only in local JVMS run Java instances, this time is not what you need the serialization and deserialization, but when we need to put in memory object persistence to disk, database, when we need to interact with the browser, when we need to implement RPC, this would require the serialization and deserialization.
Does the first two scenarios that require serialization and deserialization leave us with a big question? We don’t seem to serialize or deserialize when we interact with the browser, or persist objects in memory to the database, because we don’t implement the Serializable interface, but it works fine.
Here are the conclusions:
Serialization and deserialization are required whenever an in-memory object is persisted or transmitted over the network.
Reason:
Is it true that the server does not use the Serializable interface when interacting with the browser? JSON format is actually an object into a String, so the server and browser interaction data format is actually a String, let’s look at the String source:
public final class String
implements java.io.Serializable.Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
/** Cache the hash code for the string */
private int hash; // Default to 0
/** use serialVersionUID from JDK 1.0.2 for interoperability */
private static final long serialVersionUID = -6849794470754667710L;
Copy the code
The String type implements the Serializable interface and displays the value specified serialVersionUID.
Insert into Mybatis database mapping file
<insert id="insertUser" parameterType="com.ycfxhsw.User">
INSERT INTO t_user(name, age) VALUES (#{name}, #{age})
</insert>
Copy the code
Instead of persisting the entire object to the database, we persist properties from the object to the database, and these properties are basic properties that implement the Serializable interface.
Why should Serializable interface be implemented?
After implementing the Serializable interface in Java, the JVM will implement Serializable and deserialization for us. If we don’t implement the Serializable interface, we can write our own Serializable and deserialized code.
Why specify serialVersionUID?
If the specified serialVersionUID is not displayed, the JVM automatically generates a serialVersionUID based on the property during serialization, which is then serialized with the property for persistence or network transport.
During deserialization, the JVM will automatically generate a new version of serialVersionUID based on the attributes, and then compare this new version with the old version of serialVersionUID generated during the serialization. If they are the same, the deserialization succeeds; otherwise, an error is reported.
If the serialVersionUID is specified in the display, the JVM will still generate a serialVersionUID for both serialization and deserialization, but the value will show us the specified value so that the serialVersionUID of the old and new versions is the same when deserializing.
In real development, what problems would arise if the serialVersionUID was not specified? If we don’t modify our class after we write it, that’s fine.
This is not possible in real development. Our class iterates over and over again, and as soon as the class is modified, the deserialization of the old object will report an error. So in real development, we’ll show you specifying a serialVersionUID, whatever the value is, as long as it doesn’t change.
Write an example to test:
(1) the User class
- The specified serialVersionUID is not displayed.
import java.io.Serializable;
public class User implements Serializable {
String name;
Integer age;
@Override
public String toString(a) {
return "User{" +
"name='" + name + '\' ' +
", age=" + age +
'} ';
}
// omit the get/set method
}
Copy the code
(2) the test class
- First serialize, then deserialize.
public class SerializeTest {
private static File file = new File("D:/Desktop/user.txt");
private static void serialize(User user) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(user);
oos.close();
}
private static User deserialize(a) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
return (User) ois.readObject();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
User user = new User();
user.setName("Vega");
user.setAge(18);
System.out.println("The result before serialization is: + user);
serialize(user);
User user1 = deserialize();
System.out.println("Deserialization results in:"+ user1); }}Copy the code
User{name=’ zhinv ‘, age=18}
(3) the results
- Comment out the deserialization code, execute the serialization code, and add an attribute to the User class, sex
public class User implements Serializable {
String name;
Integer age;
String sex;
@Override
public String toString(a) {
return "User{" +
"name='" + name + '\' ' +
", age=" + age +
", sex='" + sex + '\' ' +
'} ';
}
// // omits the get/set method
}
Copy the code
- Then comment out the serialization code and execute the deserialization code, resulting in the following result:
local class incompatible: stream classdesc serialVersionUID = -8867211101605543804, local class serialVersionUID = 6343365699042275217
An error was reported as serialVersionUID inconsistent with the serialVersionUID generated by deserialization.
Next we specify a serialVersionUID based on the User class above
private static final long serialVersionUID = 1L;
Copy the code
Perform the above steps again, and the test results are as follows:
User{name=’ zhinv ‘, age=18} User{name=’ zhinv ‘, age=18, sex=’null’}
The serialVersionUID inconsistency between serialization and deserialization is resolved by showing the specified serialVersionUID.
Additional features of Java serialization
To conclude, attributes modified by the TRANSIENT keyword are not serialized, and static attributes are not serialized.
Let’s test this:
(1) the User class
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private Integer age;
private transient String sex;
private static String signature = "You see the world as you see yourself.";
@Override
public String toString(a) {
return "User{" +
" + name + '\\'' + ", age=" + age + ", sex='" + sex +'\ \' ' +
", signature='" + signature + '\ \''+'}'; } // omit the get/set method}Copy the code
(2) the test class
public class SerializeTest {
private static File file = new File("D:/Desktop/user.txt");
private static void serialize(User user) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(user);
oos.close();
}
private static User deserialize(a) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
return (User) ois.readObject();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
User user = new User();
user.setName("Vega");
user.setAge(18);
user.setSex("woman");
System.out.println("The result before serialization is: + user);
serialize(user);
User user1 = deserialize();
System.out.println("Deserialization results in:"+ user1); }}Copy the code
(3) the results
Signature = “I only have eyes for you”; signature = “I only have eyes for you”; signature = “I only have eyes for you”
User{name=’ zhinv ‘, age=18, sex=’woman’, signature=’ you see the world as you see it ‘}
User{name=’ zhinv ‘, age=18, sex=’null’, signature=’ I only have eyes for you ‘}
Static attributes are not serialized.
Because serialization is for objects, static attributes take precedence over objects and are loaded as the class is loaded, so they are not serialized.
If serialVersionUID is static, why should serialVersionUID be serialized?
The serialVersionUID attribute is not serialized. The JVM automatically generates a serialVersionUID when serializing an object. We then assign the serialVersionUID property value specified by our display to the automatically generated serialVersionUID.