When serializing and deserializing, if you want to ensure that the object is unique (for example, a single case pattern), you need to be extra careful, usually in implementing a single and type-safe enumeration that occurs. In this case, the default serialization mechanism does not apply.
Public final class Singelton implements Serializable {
Private Singelton () {
}
private static final Singelton INSTANCE = new Singelton ();
public static Singelton getinstance () {
return INSTANCE;
}
}
If a single instance object is serialized, and the object is deserialized from memory
ObjectOutputStream out = new ObjectOutputStream (New FileOutputStream ("Test.dat"));
Out.writeobject (SINGLE1);
ObjectInputStream in = new ObjectInputStream (New FileInputStream ("Test.dat"));
Singelton Newsingle = (Singelton) in.readobject ();
At this time the Newsingle and Single1 is completely different, is a brand-new object, destroyed the single case principle.
To solve this problem, you need to add a special serialization Method Readresolve () method to the class. If the method is defined, it is called after the object is serialized.
Public final class Singelton implements Serializable {
Private Singelton () {
}
private static final Singelton INSTANCE = new Singelton ();
public static Singelton getinstance () {
return INSTANCE;
}
Private Object Readresolve () throws Objectstreamexception {
return INSTANCE;
}
}