In the previous posts, we saw how to store and retrieve the objects using Serialization. We’ll now look at another very important technique for storing and retrieving objects.

The Externalizable Interface:

The previous post covered the use of the Serializable interface for persisting the object state. We’ll now look at the Externalizable interface, which provides control over the serialization process.

·   If an object implements the Serializable interface, all its fields get persisted unless they are marked with the transient keyword or are declared static in the class.

·    The transient keyword was designed to meet this specific requirement of allowing the object’s field containing sensitive data not to persist. The class may hold some sensitive data, such as credit card number, encryption key, and so on, in its fields.

·     Also, the class may declare a few instance fields for its own internal workings and may also contain declarations of some temporary variables. Obviously, we won’t want to transmit such data over the network or even store it to disk.

·     We would mark such fields with the transient keyword. When we save or transmit such an object, its entire other state will be transmitted or saved.

·   Likewise, the fields that are marked with the static keyword are not serialized; this is because such fields belong to the class and not to an object.

In some situations, we may want to provide our own way to persist the object state, other than the default algorithm used by the JVM. For example, if our object is of type Customer and contains credit card numbers in one of its fields, we will not want to save this number as is.

Instead, we would encrypt this field before the Customer object is saved to persistent storage or transmitted over the network. This is where the interface Externalizable comes in handy. This interface has two callback methods:

·         readExternal ()

·         writeExternal ()

Before the object is persisted, the runtime calls these two methods. We can perform operations such as encryption and decryption in these two methods. Also, we need to write code to persist whatever fields we want to save.

The Serializable interface uses the default runtime mechanism to implement the object serialization, whereas the Externalizable interface mandates that the class handle its own serialization. This means that we need to decide which fields to write (and read) and in what order. We implement this in the writeExternal (and corresponding readExternal) method.

Because implementing the Externalizable interface mandates that we write code for serializing the desired fields of the class, the rest of the class fields need not be marked transient.

  Modified On Dec-18-2017 02:20:13 AM

Leave Comment