This article mainly introduces relevant information about serialization and readResolve() method examples in Java. Examples are provided here to help you understand this part of knowledge. Friends in need can refer to it
Detailed explanation of examples of serialization and readResolve() method in java
What is the function of readResolve method? This method is related to the serialization of objects (this explains why the readResolve method is privately modified). How is it related to the serialization of objects?
Let’s briefly review the serialization of objects. Generally speaking, if a class implements the Serializable interface, we can write it to memory and read it from memory to "assemble" it into an object that is exactly the same as the original. However, when serialization encounters a singleton, there is a problem: the object read and assembled from memory breaks the rules of the singleton. A singleton requires only one class object in a JVM, but now through deserialization, a new object is cloned. As shown in the following example:
Java code:
public final class MySingleton implements Serializable { private MySingleton() { } private static final MySingleton INSTANCE = new MySingleton(); public static MySingleton getInstance() { return INSTANCE; } }
When the MySingleton object (the singleton object obtained through the getInstance method) is serialized, then from When read from memory, a new but identical MySingleton object exists. So how to maintain the singleton mode? This requires the use of the readResolve method. As shown below:
public final class MySingleton implements Serializable{ private MySingleton() { } private static final MySingleton INSTANCE = new MySingleton(); public static MySingleton getInstance() { return INSTANCE; } private Object readResolve() throws ObjectStreamException { // instead of the object we're on, // return the class variable INSTANCE return INSTANCE; } }
In this way, when the JVM deserializes and "assembles" a new object from memory, it will automatically call this readResolve method. The object we specified is returned, and the singleton rule is guaranteed.
The above is the detailed content of Detailed explanation of the use of serialization and readResolve() method in Java. For more information, please follow other related articles on the PHP Chinese website!