Wednesday, May 27, 2015

Using serialver JDK command

If you are implementing java.io.Serializable, it is a good practice to create the serialVersionUID for that class.  Otherwise, when the class structure is changed (adding or removing the attributes), you will have the nightmare of handling the different serialVersionUID issues.

You can provide any random value to the serialVersionUID but it is better to let the tools generate the unique IDs for each class.

Eclipse comes with the built-in serialVersionUID option to generate the unique UID.  However, if the project is not compiled successfully (typically the dependencies issues), or if you don't want Eclipse to build your project, generating the version UID is not possible.

That is where serialver command line comes to the rescue.  The format is:

serialver [-classpath classpath] [-show] [className]

[-classpath classpath] - is where your class files' root folder.  For ex. if you have <myfolder>/target/classes/com/mytest/MyOnlyTest.class, then your class files root folder is <myfolder>/target/classes/.  

Most of the times the classpath value is required.  If you run the serialver command from "<myfolder>/target/classes", the classpath value will be "./".  It is always better to start from the folder where the root package is the subdirectory of that.

[-show] - This will provide UI option.  This will work just like the command line.

[className] - The fully qualified class name (that is including the package name).  For ex. com.mytest.MyOnlyTest

Example  (Using the command line):

c:\<myfolder>\target\classes>serialver -classpath "./" com.mytest.MyOnlyTest

If the class is a valid one, you will see the serialVersionUID entry like this:

com.mytest.MyOnlyTest:  static final long serialVersionUID = -7039383885342506716L

Copy that value and paste it in your java file.

Example (Using the UI):

c:\<myfolder>\target\classes>serialver -classpath "./" -show

This will display a small box with entering the full class name.  Enter com.mytest.MyOnlyTest, then click "Show".  If the class is a valid one, you will see the serialVersionUID entry in the "Serial Version" box.  

Copy that value and paste it in your java file.

Note: If you get the <className> is not found, check whether you entered the right class path value.