directory
- Serialization and deserialization
- When do you need to serialize and deserialize?
- Why implement Serializable interface?
- Why display the value of the serialVersionUID specified when implementing the Serializable interface?
- Additional features of Java serialization
- Why are static attributes not serialized?
The Serializable interface should be implemented for all classes in the model package, and the value of serialVersionUID should also be displayed. Several questions popped into my mind when I heard this need, such as:
- What are serialization and deserialization?
- Why implement Serializable interface?
- Why display the value of the serialVersionUID specified when implementing the Serializable interface?
- What value do I specify for serialVersionUID?
Let’s answer them one by one.
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 do you need to serialize and deserialize?
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.02. for interoperability \*/
private static final long serialVersionUID = - 6849794470754667710.L; . }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="org.tyshawn.bean.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 implement the Serializable interface?
If Serializable interface is not implemented in Java, the JVM will implement Serializable and deserialization for you. If Serializable interface is not implemented in Java, the JVM will implement Serializable and deserialization code for you. Just Google it.
Why specify the value of 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.
public class User implements Serializable {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
" + name + '\\'' + ", age=" + age + '}'; }}Copy the code
(2) the test class
First serialize, then deserialize.
public class SerializableTest {
private static void serialize(User user) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("D:\\\\111.txt")));
oos.writeObject(user);
oos.close(a); } private static User deserialize() throws Exception{ ObjectInputStream ois =new ObjectInputStream(new FileInputStream(new File("D:\\\\111.txt")));
return (User) ois.readObject();
}
public static void main(String\[\] args) throws Exception {
User user = new User();
user.setName("tyshawn");
user.setAge(18);
System.out.println("Result before serialization:" + user);
serialize(user);
User dUser = deserialize();
System.out.println("Deserialized result:"+ dUser); }}Copy the code
(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 {
private String name;
private Integer age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User{" +
" + name + '\\'' + ", age=" + age + ", sex='" + sex + '\ \' ' +
'} '; }}Copy the code
Then comment out the serialization code and execute the deserialization code, resulting in the following result:
Results before serialization: User {name = ‘tyshawn’, the age 18} = the Exception in the thread “is the main” Java. IO. InvalidClassException: org.tyshawn.SerializeAndDeserialize.User; local class incompatible: stream classdesc serialVersionUID = 1035612825366363028, local class serialVersionUID = -1830850955895931978
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=’tyshawn’, age=18} {name=’tyshawn’, 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.";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public static String getSignature() {
return signature;
}
public static void setSignature(String signature) {
User.signature = signature;
}
@Override
public String toString() {
return "User{" +
" + name + '\\'' + ", age=" + age + ", sex='" + sex +'\ \' ' +
", signature='" + signature + '\ \''+'}'; }}Copy the code
(2) the test class
public class SerializableTest {
private static void serialize(User user) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("D:\\\\111.txt")));
oos.writeObject(user);
oos.close(a); } private static User deserialize() throws Exception{ ObjectInputStream ois =new ObjectInputStream(new FileInputStream(new File("D:\\\\111.txt")));
return (User) ois.readObject();
}
public static void main(String\[\] args) throws Exception {
User user = new User();
user.setName("tyshawn");
user.setAge(18);
user.setSex("man");
System.out.println("Result before serialization:" + user);
serialize(user);
User dUser = deserialize();
System.out.println("Deserialized result:"+ dUser); }}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=’tyshawn’, age=18, sex=’man’, signature=’ you see the world as you see it ‘} User{name=’tyshawn’, age=18, sex=’null’, signature=’ I only have eyes for you ‘}
Why are static attributes 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.
From: tyshawnlee.blog.csdn.net/article/details/100097019