Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate serialVersionUID programmatically in Java?

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.

like image 316
bn. Avatar asked Aug 17 '13 23:08

bn.


People also ask

How do I generate serialVersionUID?

Once you've enabled this plugin, you just need to press Alt+Insert / Command+n when you are in the body of a class implementing the Serializable interface. You should see an option to generate the serialVersionUID field for you.

How serialVersionUID is generated when it's not defined in code?

If class does not contain a serialVersionUID field, its serialVersionUID will be automatically generated by the compiler. Different compilers, or different versions of the same compiler, will generate potentially different values.

What is serialVersionUID 1l in Java?

The serialization at runtime associates with each serializable class a version number called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.


1 Answers

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.

like image 175
c.s. Avatar answered Oct 13 '22 01:10

c.s.