Java Serialization: Class 9

5) EXTERNALIZATION:

This is concept is not well known to everyone. But it is very important and beautiful concept. Here are some points to understand Externalization.

a) In Serilaization everything takes care by JVM and programmer doesn't have any control. In Serialization total Object will be saved always to the file and it is not possible to save part of the Object which creates performance problems. To overcome these problems we should go for externalization where everything takes care by programmer and JVM doesn't have control.

b) The main advantage of Externalization over Serialization is based on our requirement. we can save either total Object or part of the Object so that relatively performance will be improved.

c) to provide externalization ability for java Object compulsory the corresponding class should implements Externalization Interface.

Note: Externalizable Interface present in java.io Package and it is the child Interface of Serialization.

Externalizable Interface contains 2 Methods
a) writeExternal()
b) readExternal()


public void writeExternal(ObjectOutput out) throws Exception

a) This method will be executed at the time of serialization.
b) Within this method we have to write code to save the required variables to the file.

public void readexternal(ObjectInput in) throws exception, ClassNotFoundException

a) This method will be executed automatically at the time of De-serialization.
b) Within this method we have to write code to read required variables from the file and assign it to current Object.
c) Strictly speaking at the time of De-serialization JVM will create a separate new Object by executing public no-argument Constructor. On the Object readExternal() method will be executed.
d) Hence every Externalizable interface implemented class should contain public no-argument constructor. Otherwise we will get run time Exception saying InValidClassException.

As in case externalizable, in spite of saving complete object to a file, we save only required properties to the file. But at the time of De-Serialization, we do not need properties but we need an Object. Therefore, at the time of De-Serialization JVM will create a new Object and call readExternal() method. Now, it's readExternal() method's responsibility to assign the properties to the new Object .

Note: Every Externalizable implemented class must have a no-argument constructor. Because at the time of De-Serialization, JVM calls public no-argument constructor. Then the new Object will have it's properties values as default and the readExternal() method will replace the corresponding properties values from null to the value in file.


Share on Google Plus

About Unknown

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.

0 comments:

Post a Comment