Serialization

Object serialization takes an object's state and converts it to a stream of data for persistance.



To make an object serializable, the class must implement java.io.Serializable. It is a marker interface; no extra methods need to be implemented.



Let's say you have myObject that is serializable. Writing following code will persist myObject for later use.



// Use a FileOutputStream to send data to a file

// called myobject.data.

FileOutputStream fileOut = new

FileOutputStream ("myobject.data");



// Use an ObjectOutputStream to send object data to the

// FileOutputStream for writing to disk.

ObjectOutputStream objOut = new

ObjectOutputStream (fileOut);



// Pass our object to the ObjectOutputStream's

// writeObject() method to cause it to be written out

// to disk.

objOut.writeObject (myObject);




To restore serialized object:

// Read from disk using FileInputStream.

FileInputStream fileIn = new

FileInputStream ("myobject.data");



// Read object using ObjectInputStream.

ObjectInputStream objIn = new ObjectInputStream (fileIn);



// Read an object.

Object obj = objIn.readObject ();



// Is the object that you read in, say, an instance

// of the Vector class?

if (obj instanceof Vector)

{

// Cast object to a Vector

Vector vec = (Vector) obj;



// Do something with vector ...

}

else // ... the object is some other type ...




If there's any member variable that should not be serializable, you can use "transient" key word:

public class UserSession implements java.io.Serializable

{

String username;

transient String password;

}