Monday, October 17, 2011

What is object serialization?


What is object serialization?

You can think in serialization as the process to convert an object instance, into a sequence of bytes ( which may be binary or not depends on the implementation ) .
It is very useful when you want to transmit one object data across the network, for instance from one JVM to another.
In Java, the serialization mechanism is built-in the platform, but you need to let the program you want an object to be serializable by implementing the Serializable interface.
You can also, prevent some data in your object from being serialized, by marking the attribute astransient
Finally you can override the default mechanism, and provide your own, this may be suitable in some special cases. To do this, you use one of the hidden features in java.
It is important to notice that what gets serialized is the "value" of the object, or the contents, and not the class definition. Thus methods are not serialized.
Here is a very basic sample with comments to facilitate its reading:
import java.io.*;
import java.util.*;
// This class implements "Serializable" to let the system know
// it's ok to do it. You as programmer are aware of that.
public class SerializationSample implements Serializable {

    // These attributes conform the "value" of the object.

    // These two will be serialized;
    private String aString = "The value of that string";
    private int    someInteger = 0;

    // But this won't since it is marked as transient.
    private transient List<File> unInterestingLongLongList;

    // Main method to test.
    public static void main( String [] args ) throws IOException  { 

        // Create a sample object, that contains the default values.
        SerializationSample instance = new SerializationSample();

        // The "ObjectOutputStream" class have the default 
        // definition to serialize an object.
        ObjectOutputStream oos = new ObjectOutputStream( 
                                     // By using "FileOutputStream" we will 
                                     // Write it to a File in the file system
                                     // It could have been a Socket to another 
                                     // machine, a database, an in memory array, etc.
                                     new FileOutputStream(  new File("o.ser")) ) ;

        // do the magic  
        oos.writeObject( instance );
        // close the writing.
        oos.close();
    }
}
When we run this program, the file "o.ser" is created and we can see what happened behind.
If we change the value of: someInteger to , for example Integer.MAX_VALUE we may compare the output to see what the difference is.
Here's an screenshot showing precisely that difference:

alt text

0 comments: