Thursday, 13 April 2017

Java Serialization with Aggregation (HAS-A Relationship)

If a class has a reference to another class, all the references must be Serializable otherwise serialization process will not be performed. In such case, NotSerializableException is thrown at runtime.

Address.java
class Address { 
     String hNo,city,state; 
     public Address(String hNo, String city) { 
           this.hNo=hNo; 
           this.city=city; 
     } 
}

Employee.java
import java.io.Serializable; 
public class Employee implements Serializable { 
     int id
     String name
     Address address;//HAS-A 
     public Employee(int id, String name) { 
           this.id = id
           this.name = name
     } 

Since Address is not Serializable, we are getting NotSerializableException while serializing the instance of Employee class.

How to fix the Serialization in the case of Association?
Using the transient keyword:
In case the class refers to non-serializable objects and these objects should not be serialized, then, you can declare these objects as transient. Once a field of a class is declared as transient, then, it is ignored by the serializable runtime.

Using the static keyword:
In serialization, static variables are not serialized, so during deserialization, static variable value will load the class.

Make it a Serializable object:
All the objects within an object must be Serializable.

3 comments:

Related Posts Plugin for WordPress, Blogger...