Thursday, 3 February 2011

Serializing an Object

1) Serializable does not define any methods. It tells the JVM that a class can be serialized.
2) If your class extends a class that doesn't implement Serializable then that super class must have a default (no argument) constructor to initialise the itself during de-serialization.
3) If you try to serialize a class that doesn't implement Serializable then a NotSerializableException run time exception is thrown.
4) Serialization is done through a classes that implement the ObjectOutputStream and the corresponding ObjectInputStream interface.


Serializing an Object

try {
        FileOutputStream aFOS = new FileOutputStream("myfile.ser");
        ObjectOutputStream aOOS = new ObjectOutputStream(aFOS);

        // create the object to be serialized...
        Serializee s = new Serializee();

        System.out.println("Created new object with value: " + s.getNumber());

        aOOS.writeObject(s);
        aOOS.flush();
        aFOS.close();
    } catch(IOException ioe) {
        System.out.println(ioe.getMessage());
    }

No comments: