StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Friday, March 7, 2014

Java Serialization

 March 07, 2014     Java     No comments   

In this article, we will work with Java Serialization to convert an object to byte stream and back.

Java Serialization Introduction

Serialization is the process of converting the current state of an object into a byte stream. Deserialization is the process of converting the serialized form of an object back into a copy of the object. A Java object is Serializable if a class implements java.io.Serializable interface. java.io.Serializable is a marker interface which tells that object is Serializable.

A quick example. In this example, Employee class implements the marker interface Serializable and can be serialized.

package com.sourcetricks.java;

import java.io.Serializable;

public class Employee implements Serializable {

 private static final long serialVersionUID = 2L;
 private int id;
 private String name;
 private int deptId;
 Employee() {   
 }
 Employee(int id, String name, int deptId) {
  this.id = id;
  this.name = name;
  this.deptId = deptId;
 }
 public int getId() {
  return id;
 }
 public String getName() {
  return name;
 }
 public int getDeptId() {
  return deptId;
 }
 public void setId(int id) {
  this.id = id;
 }
 public void setName(String name) {
  this.name = name;
 }
 public void setDeptId(int deptId) {
  this.deptId = deptId;
 }
 public void print() {
  System.out.println(id);
  System.out.println(name);
  System.out.println(deptId);
 }
}
In the test program we create an instance of Employee and using writeObject on ObjectOutputStream we persist the serialized object to the file system. During deserialization we do the reverse using readObject on ObjectInputStream to create a copy of the object back.
package com.sourcetricks.java;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class JavaSerializationTest {
 
 public static void main (String[] args) {
  
  Employee e = new Employee(100, "John", 14);
  e.print();
  
  // Serialize and save the object to file
  FileOutputStream fout = null;
  ObjectOutputStream out = null;
  try {
   fout = new FileOutputStream("data.out");
   out = new ObjectOutputStream(fout);
   out.writeObject(e);
   out.close();
   fout.close();
  } catch (IOException e1 ) {
   e1.printStackTrace();
  }
  
  // Read object from file
  FileInputStream fin = null;
  ObjectInputStream in = null;
  try {
   fin = new FileInputStream("data.out");
   in = new ObjectInputStream(fin);
   Employee e1 = (Employee) in.readObject();
   e1.print();
   in.close();
   fin.close();
  } catch (IOException e1 ) {
   e1.printStackTrace();
  } catch (ClassNotFoundException e2) {
   e2.printStackTrace();
  }
 }
}

Output:
100
John
14
100
John
14

Significance of serialVersionUID

serialVersionUID is important for classes to be serialized. It allows to specify a version to the object. Lets say object version is 1 when the object was written to the file system. At a later point of time there is a type change in the object and the version is upgraded to 2. If we try to deserialize the original object written to file system then it results in an InvalidClassException.

java.io.InvalidClassException: com.sourcetricks.java.Employee; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2

Significance of transient

Sometimes it is necessary that one of the class members should not be included as part of the serialization process. Either it has sensitive information or which is not relevant once the object is de-serialized. (e.g. current time). In such scenarios associating transient keyword prevents the class member from being included as part of writeObject.
Email ThisBlogThis!Share to XShare to Facebook
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Python FastAPI file upload and download
    In this article, we will look at an example of how to implement a file upload and download API in a Python FastAPI microservice. Example bel...
  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Accessing the Kubernetes API
    In this article, we will explore the steps required to access the Kubernetes API and overcome common challenges. All operations and communic...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Scheduling jobs in Python
    When developing applications and microservices we run into scenarios where there is a need to run scheduled tasks. Examples include performi...
  • Using Tekton to deploy KNative services
    Tekton is a popular open-source framework for building continuous delivery pipelines. Tekton provides a declarative way to define pipelines ...

Copyright © StackStalk