Monday, September 1, 2014

How does JVM evaluate serialVersionUID if not provided explictly ?

If the programmer does not provide the serialVersionUID explicitly, then the jvm defaults the id to the hash* for that class. The serialVersionUID is a 64-bit (long type) hash of the class name, interface class names, methods, and fields.


private static final long serialVersionUID = 3487495895819393L;

hash* - The hash mentioned here does not refer to the one calculated from hashCode() method. 

Java api provides the utilities to evaluate the serialVersionUID. It may be evaluated 
a) programatically through the api exposed by java
b) through the utility 
serialver provided in the bin folder.


a) Programatically evaluating the serialVersionUID :  Java api provides class ObjectStreamClass, that can be used as below to evaluate the serialVersionUID of a class.
Here we are evaluating the serialVersionUID of the Person class.

We can tweak the class structure by adding/removing new fields,  interfaces, methods, changing access-modifiers etc and we can verify that the serialVersionUID changes.

import java.io.ObjectStreamClass;

public class EvaluateSerialVersionUID {

 public static void main(String[] args) {
  ObjectStreamClass osc = ObjectStreamClass.lookup(Person.class);
  System.out.println(osc.getSerialVersionUID());
 }
}

b) serialver.exe utility in the JDK bin directory : 

We can also use the serialver.exe utility to evaluate the SerialVersionUID in a serializable class.



import java.io.Serializable;
public class Test implements Serializable{
 String name;
 
 public Test(){}
 
 public Test(String name){
  this.name= name;
 }
}

Compile the Test class.
Open command prompt, change the directory to the JAVA_HOME/bin directory.
Run the below command. ( D:\Java_Workspace is path containing Test.class file ).

serialver -classpath D:\Java_Workspace -show





Enter the fully qualified class name and click show.




No comments:

Post a Comment