How to generate serialVersionUID programmatically in Java?

bn. picture bn. · Aug 18, 2013 · Viewed 11.7k times · Source

I am working on a project that generates Java files. I'd like to be able to optionally add the serialVersionUID as you would with the serialver tool.

Is there a way to do this when I generate the Java code, or will I need to ask the user of the tool to provide UIDs manually? To be clear, I'm not looking to do this automatically through Eclipse or the serialver tool, but to do it via Java itself.

Answer

c.s. picture c.s. · Aug 18, 2013

There is a version of the serialver tool source available from OpenJDK. It all comes down to this call:

ObjectStreamClass c = ObjectStreamClass.lookup(MyClass.class);
long serialID = c.getSerialVersionUID();
System.out.println(serialID);

In JDK 6 at least it returns the same number with serialver tool.