Serialize static variable in java - Java @ Desk

Wednesday, July 24, 2013

Serialize static variable in java

Can we serialize static variable in java?
No. Since static members are associated with the class and they do not belong to the individual objects, they are not serialized. Static field values will be reinitialized to whatever value they are set to when the class is loaded.
Consider a below class with a static field with initial value as 10.

Person.java
 package com.serialization;  
 import java.io.Serializable;
 public class Person implements Serializable {  
   private static final long serialVersionUID = -8935100740005343248L;
   static int staticField = 10; 
   private String firstName;  
   private String lastName;  
   public Person(String firstName, String lastName) {  
     super();  
     this.firstName = firstName;  
     this.lastName = lastName;  
   }  
   public String getFirstName() {  
     return firstName;  
   }  
   public void setFirstName(String firstName) {  
     this.firstName = firstName;  
   }  
   public String getLastName() {  
     return lastName;  
   }  
   public void setLastName(String lastName) {  
     this.lastName = lastName;  
   }  
 }  
SerializationMain.java - In this class, update the static field value to 20 as shown below and then serialize the class
 package com.serialization;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.io.ObjectOutputStream;  
 public class SerializationMain {  
   public static void main(String[] args) throws IOException {  
     Person person = new Person("Kumar", "Bhatia");  
     // Update static field to some value and then serialize
     Person.staticField = 20;
     System.out.println("person " + person);  
     FileOutputStream fos = new FileOutputStream("serial.txt");  
     ObjectOutputStream oos = new ObjectOutputStream(fos);  
     oos.writeObject(person);  
     oos.flush();  
     oos.close();  
   }  
 }  
DeSerializationMain.java - Once we de-serialize the Person object, the value of staticField will be initialized to 10 as shown below but not 20 as done in SerializationMain.java
 package com.serialization;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 import java.io.ObjectInputStream;  
 public class DeSerializationMain {  
   public static void main(String[] args) throws IOException, ClassNotFoundException {  
     FileInputStream fis = new FileInputStream("serial.txt");  
     ObjectInputStream ois = new ObjectInputStream(fis);  
     Person person = (Person) ois.readObject();  
     ois.close();  
     System.out.println("person " + person.staticField);  
   }  
 }  









No comments:

Post a Comment