Serialization tutorial – Part IV

You can go through the part III here, If you haven’t yet.

serialVersionUID

Let us now only serialize the object DerivedTestObject. So object will be converted into byte streams and saved into the file.

package Serialization;

public class SerializationTest {
       public static void main(String[] args) {
              DerivedTestObject tObj1 = new DerivedTestObject (100, "TestSerialization", new OtherObject());
              SerializeUtility utility = new SerializeUtility();

              // serialization
              utility.serialize(tObj1);
       }
}

Now, consider adding a new field to DerivedTestObject class. New field could be of any type. Lets add a String type new field as shown below:

Continue reading

Advertisements

Serialization tutorial – Part III

You can go through the part II here, If you haven’t yet.

How to customize Serialization:

Anyhow, Java handles serialization process then what’s the need of customizing it. Let’s look at a small scenario.

Let’s consider our TestObject class has a transient field so that it cannot get serialized and imagine we do not have the source code for this class and we have a requirement that we need to get this field serialized which has defined as transient in the source code like below.

Continue reading

Serialization tutorial – Part II

You can go through the part I here, If you haven’t yet.

Transient keyword:

When we have a class which implements Serializable interface, that means its eligible for getting serialized but we want few fields not to get serialized then we can place the transient keyword before their declarations to tell the serialization mechanism that the field should not be saved along with the rest of that object’s state. Then those transient fields will not be serialized. That means their values will not be saved into bytestream while serialization. While deserialization those transient fields will be stored back into the object with their data types’ default values.

For example,

Continue reading

Serialization tutorial – Part I

What is serialization and how its performed?

Serialization is a mechanism through which we can save the state of an object by converting the object into a byte stream.

Serialized object (byte stream) can be transferred over network, persisted or saved into file/database.

We can deserialize the Serialized object (byte stream) and gets back the original object.

Let’s try to write a Java program to serialize an object.

Continue reading