Serialization and deserialization in Java

2022-09-02 0 By

Basic Concepts When an object is created in Java, it may not exist once the program terminates.To make objects in the program does not run to save the object information, then you need to use the serialization mechanism serialization mechanism: data object type information is stored in the object in the data type of an object can be represented as a sequence of bytes, including: to write a serializable object into the file, can be read from a file, according to the objectVarious information creates the object in memory.The process of reading and creating an object here is deserialization and the entire process of deserialization is JVM independent.That is, a serialized object in one JVM can be deserialized in a completely different JVM. In general, serialization requires implementing the Java.io.Serializable interface, using ObjectInputStream and ObjectOutputStream for reading and writing objectsThe operation can also implement the java.io.Externalizable interface for standard serialization or custom binary formats.Java serialization scenario: Persisting the byte sequence of a Java object to a hard disk. Transferring the byte sequence of an object over the network for Remote Method invocation (RMI)The object created needs to be saved for subsequent transport so that the object created by the old JVM can run in a new JVM with Java serialization. Note: The serialization of the object stores the object member variable object, and the serialization of the object does not focus on static variables in the classSerialization of a class ensures that all attributes of the class are serializable, if you want an attribute not to be serialized.Java object serialization: Make Serializable objects implement the Serializable interface. Create an ObjectOutputStream output stream. Call writeObject() of ObjectOutputStream.The serializable object can be serialized example:Deserialize Java Objects Deserialize: Create an ObjectInputStream input stream and call ObjectInputStream’s readObject().Deserialized objects are objects generated by the JVM, not by the constructor of the class: deserialized objectsIf the member of a Serializable class is not a primitive type but a reference type, then the reference type must implement the Serializable interface. Otherwise, NotSerializabl will be thrownEException And deserialization Summarize why Serializable can be serialized by implementing the Serializable interface: Every object saved to disk has a serialization number. When a program attempts to serialize an object, it checks whether the object has been serialized and only serializes the object as a sequence of bytesThe Java serialization mechanism does not serialize the same object repeatedly, but records the number of the serialized object. In this case, if a variable object is serialized, it will be serialized again if the contents of the object are changed.If does not change the content, not converts the object to a sequence of bytes, will only save the serialization number first will be written before processing and non-replaceable object if some objects are replaced, the inspection is replaced object if the object is to replace the last, the original check the original check that checks if the object type is substituted for the String type, array typeIf the Serializable interface is implemented, Serializable objects can be serialized, otherwise NotSerializableException writeObject() will be thrown: For serialization mechanisms, if the same object is executed more than onceWhen Serializable, the writeObject() and readObject() methods can be overridden.The writeObject() and readObject() methods are automatically called when the object is serialized or deserialized. When implementing the Externalizable interface, the writeExternal() and readExternal() methods can be overwritten.Methods: After overwriting the writeExternal() and readExternal() methods, the overwritten writeExternal() and readExternal() methods are automatically called when objects are serialized and deserialized.Externalizable If one part of the object can be serialized and the other part can not be serialized, you can customize the Externalizable interface and implement writeExternal() and readExternal().Methods can be automatically called during serialization and deserialization to perform some special operations. Note: Objects implemented by the Serializable interface are related to binary construction, and constructors are not called. All constructors of objects implemented by the Externalizable interface are called, so write both no-parameter and no-parameter classesThe Externalizable custom serialization example constructor uses Externalizable:When using Externalizable custom serialization, to ensure proper serialization and deserialization, the information needs to be written to the writeExternal() method and readExternal() method.Method to restore data transient you can use the transient keyword to configure some important information such as passwords and so on. Properties that are not serialized transient do not participate in the serialization process. Properties that are not serialized transient do not participate in the serialization processull. If it is a basic data type, the default value is returned.Since objects implementing the Externalizable interface do not hold any fields by default, the TRANSIENT keyword can only be used with Serializable objects when the server sends serialization to the clientData, the object of sensitive data such as passwords, encrypted during serialization, the client has the decryption key, only when the client deserialize, will read the password then it can be using transient modification for password string objects, so that we can to a certain extent the static variable sequence object serialized data securityWhen you serialize, you don’t serialize static variables that are the state of the class, that’s the object, that’s the state of the instance of the class, that’s the state of the class.Serialization IDJava VIRTUAL machine deserialization: the classpath and function code of the two classes are the same. The serialization ID of the two classes, namely, serialVersionUID, is the same. The function code is the same.The Serializable interface of A and B is Serializable. The Serializable interface of A and B is Serializable. The Serializable interface of B and B is Serializable1L A non-duplicate value of type LONG randomly generated from the class name, interface name, method name, and attribute. If the serialization ID (serialVersionUID) is the same, the serialized object can be deserialized even if the serialized attribute of the serialized object is changed.So if you just change a method or change a static variable or a transient variable, as long as you don’t change the serialization ID, then deserialization won’t be affected by explicitly declaring the serialization ID,This is the serialVersionUID scenario: if different versions of a class are required to be serialized compatible, ensure that different versions of a class have the same serialVersionUID. If not, ensure that different versions of a class have different serialVersionUID serializationIf you modify a field or add a field after a class instance, if the serialVersionUID of the class is not set,Will cause cannot deserialize the old instance, will throw an exception when a deserialized serialization class after adding SerialVersionUID, if you modify a field, or add a field, the deserialization of the old instance, modify or increase the value of the field will be set to initialize the value of the destruction of the singleton besides reflection can destroy the singleton pattern, serialization andDeserialization results in a new object, which can also break the singleton pattern serialization and deserialization break the singleton pattern:To deserialize, call the readObject0() method readObject0() using the readObject() method of ObjectInputStream.The checkResolve(readOrdinaryObject(unshared)) readOrdinaryObject() method is used to read and return ordinary objects.Ordinary objects here don’t include String, Class, ObjectStreamClass,Array or enumeration constants such objects isInstantiable()This method returns true if a class implementing either Serializable or Externalizable interfaces can be instantiated at runtime. If Serializable at runtime, desc.newinstance () is called.Create a new object, create a new instance of the class. If the class implements the Serializable interface, call the first non-serializable superclass with no arguments. If the class implements the Externalizable interface, call the public no-arguments constructorCreate a new instance isInstantiable()This method returns true if a class implementing either Serializable or Externalizable interfaces can be instantiated at runtime. If Serializable at runtime, desc.newinstance () is called.The readOrdinaryObject() method uses reflection to call the no-argument constructor to create a new object, create a new instance of the class, and read and return the ordinary object.Ordinary objects here don’t include String, Class, ObjectStreamClass,ReadObject0 () returns a checkResolve(readOrdinaryObject(unshared)) deserialization. Use the readObject() in ObjectInputStreamCall readObject0() in the readObject() method.To prevent serialization from breaking the Singleton pattern, add readResolve() to singleton.java.Method and specify the generation strategy for the object to return because hasResolveMethod() in the readOrdinaryObject() method source code means that if a class implementing the Serializable or Externalizable interfaces contains readResolve()The trueinvokeReadResolve() method calls the readResolve() method of the class to be deserialized by reflection.https://juejin.cn/post/7068277615689367589