At work I have been tasked with some Java serialization issues and I needed a quick way to get the serialversionUid from a class.

I tried the serialver command that comes with the JDK, but I didn't like that I had to setup the full classpath (which for us can be quite large, lots of jars and directories). Instead I wanted it to work in my Eclipse environment which already has this classpath set and is always updated.

I found this site that had a simple way of doing it:
http://www.jguru.com/faq/view.jsp?EID=42982
Thanks Tim!

I wrote up a little wrapper main function:

  1. import java.io.ObjectStreamClass;
  2. public class SerialVer {
  3.     public static void main(String[] args)
  4.         throws ClassNotFoundException {
  5.         if(args.length != 1) {
  6.             System.err.println("Must pass a class name!");
  7.             System.exit(-1);
  8.         }
  9.         Class cclass = Class.forName(args[0]);
  10.  
  11.         long uid =
  12.             ObjectStreamClass.lookup(cclass).getSerialVersionUID();
  13.        
  14.         StringBuffer sb = new StringBuffer();
  15.         sb.append(cclass.getName());
  16.         sb.append(":\t");
  17.         sb.append("static final long serialVersionUID = ");
  18.         sb.append(uid);
  19.         sb.append("L");
  20.         System.out.println(sb.toString());
  21.     }
  22. }