Serialization is a process of converting the object into byte
stream which can send over network or save as a file or in database and same
byte stream can be de-serialize into object.
Java object can be serialize if it implements java.io.serializable
interface or its sub interface java.io.externalizable.
Java.io.Serilizable is a marker interface, has no data member and
methods. Marker interface is used to inform compiler that the class
implementing it has some special behavior or meaning.
Some other marker interface are java.lang.Cloneable and
java.util.RandomAccess but marker interface are replaced with Annotation, they
do the same behavior as the marker interface do.
If a superclass is serializable than all subclasses of that class
implements serializable implicitly serialize.
If any class in (super class) in hierarchy is not serialize than
the class is not serializable.
Static variable are never saved as part of the object state.
Note: During deserialization constructor doesn’t
invoked for those classes which implements serilazable interface.
Java Serialization-
import java.io.*;
/**
* Here we are Serializing/deserializing
the Person object
* @author Manoj
*/
public class SerializationTest {
public static void main(String args[]) throws Exception {
Person person = new Person("Manu");
FileOutputStream fout = new FileOutputStream("test.ser");
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(person);
out.flush();
out.close();
FileInputStream fileInputStream = new FileInputStream("test.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Person serPerson = (Person) objectInputStream.readObject();
System.out.println(serPerson.getName());
objectInputStream.close();
}
}
class Person implements Serializable {
private String name;
Person(String name){
this.name = name;
}
public String
getName() {
return name;
}
}
Java Serialization(Using transient)-
Transient variable are skipped during serialization, so if you don’t
want to save the state of any variable during serialization then declare it as
transient. We can handle the transient variable by overriding writeObject and
readObject method.
Refer below code snippet.
/**
* If we want to skip a variable in serilization
than declare
* it as transient and use writeObject and
readObject method
* of ObjectOutputStream and ObjectInputStream
class
* @author Manoj
*/
class Person implements Serializable {
private transient String address;
private String name;
Person(String name, String address){
this.name = name;
this.address = address;
}
private void writeObject(ObjectOutputStream objectOutputStream) {
try {
objectOutputStream.defaultWriteObject();
objectOutputStream.writeObject(address);
objectOutputStream.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void readObject(ObjectInputStream objectInputStream){
try {
objectInputStream.defaultReadObject();
String address = (String) objectInputStream.readObject();
System.out.println(address);
} catch (ClassNotFoundException | IOException e) {
System.out.println(e.getMessage());
}
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
}
Java Serialization(Using static)-
Static variables belong to a class and not to any individual
instance. The concept of serialization is concerned with the object’s current
state. Only data associated with a specific instance of a class is serialized,
therefore static member fields are ignored during serialization.
Refer below code snippet-
package com.mk.study.journal.task;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class SerilizationStaticMember {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person = new Person("123", "first test", "last test", "India");
FileOutputStream fout = new FileOutputStream("test.ser");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fout);
objectOutputStream.writeObject(person);
FileInputStream fileInputStream = new FileInputStream("test.ser");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Person serPerson = (Person) objectInputStream.readObject();
System.out.println(serPerson.getFirstName());
System.out.println(serPerson.getLastName());
System.out.println(serPerson.getId());
System.out.println(serPerson.getAddress());
objectOutputStream.flush();
objectOutputStream.close();
objectInputStream.close();
}
}
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String firstName;
private String lastName;
private transient String address;
Person(String id, String firstName, String lastName, String address) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
}
private void writeObject(ObjectOutputStream objectOutputStream) {
try {
objectOutputStream.defaultWriteObject();
objectOutputStream.writeObject(address);
objectOutputStream.writeObject(id);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
private void readObject(ObjectInputStream objectInputStream) {
try {
objectInputStream.defaultReadObject();
String address = (String) objectInputStream.readObject();
String id = (String) objectInputStream.readObject();
System.out.println(address); // this will read the transient object
System.out.println(id); // this will read the static object
} catch (ClassNotFoundException | IOException e) {
System.out.println(e.getMessage());
}
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getId() {
return id;
}
public String getAddress() {
return address;
}
}
Java Externalization-
Externalization is nothing just an extension of serialization.
Externalization provide full control over serialization process.
Unlike Serializable interface, Externalizable interface is not a
marker interface and it provides two methods - writeExternal and readExternal.
These methods are implemented by the class to give the class a complete control
over the format and contents of the stream for an object and its supertypes. These
methods must explicitly coordinate with the supertype to save its state. These
methods supersede customized implementations of writeObject and readObject
methods.
Code snippet-
import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
/**
* This class contain externalization sample
code
* @author Manoj
*/
public class ExternalizationTest {
public static void main(String[] args) {
Student serStudent = new Student("Ram", 26);
Student deSerStudent = null;
try {
FileOutputStream fos = new FileOutputStream("tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(serStudent);
oos.flush();
oos.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
FileInputStream fis = new FileInputStream("tmp");
ObjectInputStream ois = new ObjectInputStream(fis);
deSerStudent = (Student) ois.readObject();
ois.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
class Student implements Externalizable {
private String name;
private int age;
//for externalization need default public
constructor
public Student() {
super();
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
public void readExternal(ObjectInput objectInput) throws IOException, ClassNotFoundException
{
name = (String) objectInput.readObject();
age = objectInput.readInt();
}
public void writeExternal(ObjectOutput objectOutput) throws IOException {
objectOutput.writeObject(name);
objectOutput.writeInt(age);
}
public String
getName() {
return name;
}
public int getAge() {
return age;
}
}
Serialization vs Externalization-
1.
Serialization is
default serialization process to store the state of the object.
2.
Externalization
provide full control on serialization process via callback to readExternal()
and writeExternal() of interface java.io.Externilization.
3.
Serialization
provide partial control on object state, we can achieve this by overriding
readObject(), writeObject(), method.
4.
Externalization is
method can be accessed as they are readExternal() and writeExternal() are public
method while in Serialization readObject() and writeObject() method are private
Nice information, very usefull thanks
ReplyDeleteThanks
Delete