How to acheive the serialiazation?
How to acheive the serialiazation?
Implement the java.io.Serializable interface
Make your class to implements java.io.Serializable that menas that we are persisting our class. Remember that static variables, transient variables cannot be serialized.
Serialization is the concept of saving the state of an Object.
Suppose I have a singleton class
public class MySingleton {
private static final MySingleton INSTANCE =
new MySingleton();
private MySingleton() {
}
public static final MySingleton getInstance() {
return INSTANCE;
}
}
If you need to make your Singleton class Serializable, you must provide a readResolve() method:
/**
* Ensure Singleton class
*/
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
With the readResolve() method in place, deserialization results in the one (and only one) object -- the same object as produced by calls to the getInstance() method. If you don't provide a readResolve() method, an instance of the object is created each time you deserialize the object.