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.
There is a version of the
serialver
tool source available from OpenJDK. It all comes down to this call:In JDK 6 at least it returns the same number with
serialver
tool.Try the hashcode of the class name of the class being generated.
There could be collisions as a hashcode is not unique, but those collisions are statistically unlikely.
Here's documentation on how serialVersionUID values are generated. Its much more complex than I'd have guessed.
Because of its complexity, I'd either have the user type in the UID themselves, or just use a simple hash of the full classname.
If your tool is generating brand new code you don't have any need to compute it the way
serialver
does. Just use 1, or -1, or whatever you like.This is an old thread but, I guess, serialVersionUID is still one of the hot topics.
When I started to write Java codes, it was too hard to find and assign a unique value to serlialVersionUID variable for me. After a while, simple date time format (yyyy-MM-ddTHH:mm:ss) gave me the idea: Why don't I generate a value from current date and time?
So, I started to generate (of course manually) values according to current date and time.
Let's say current date and time is 01/09/2015 11:00pm. I would assign 201601091100L value to serialVersionUID.
I hope this idea helps you for further improvements in your projects.
From
ObjectStreamClass
: