Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically generate serial version UID in Eclipse

Tags:

java

eclipse

I frequently use the Eclipse quick fix to generate a serial version UID for serializable classes.

Is there any way to do this by default?

It's one extra click, but with Eclipse selecting quick fixes is generally slowish, and I always generate serial version UID:s when I implement serializable.

like image 614
David Berger Avatar asked Jan 17 '13 23:01

David Berger


People also ask

How do I get a serial version ID?

File -> Settings -> Editor -> Inspections -> Java -> Serialization issues : Find serialization class without serialVersionUID and check it. Back to the editor, clicks on the class name, ALT + ENTER (Windows), it will prompts the Add serialVersionUID field option. A new serialVersionUID is auto-generated.

What is serialVersionUID in Java?

SerialVersionUID is a unique identifier for each class, JVM uses it to compare the versions of the class ensuring that the same class was used during Serialization is loaded during Deserialization. Specifying one gives more control, though JVM does generate one if you don't specify.

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.


2 Answers

This is perhaps not the answer you're looking for. Presumably, you use Eclipse to generate the same special value that Java would automatically calculate for your class if you didn't explicitly specify it, something like:

    private static final long serialVersionUID = 4125965356358329466L;

But there's no good reason to rely on this same algorithm for newly authored classes. What matters is you specify a value, any value. So why not simply do the following?

    private static final long serialVersionUID = 1L;

You could then put this code in Eclipse's new class template.

like image 159
cambecc Avatar answered Sep 21 '22 08:09

cambecc


Not sure if you have got answer to this. But Eclipse does allow to create serialVersionUID in one go for all classes implementing Serializable. Although, it is not exactly same what you want. However, it will serve the purpose with fewer clicks.

Right-click Project -> Source -> Clean Up...

  • Select Use custom profile. then click Configure

clean-up-screen-1

  • Click Missing Code tab. Under Potential programming problems select Add serial cersion ID. Click OK

clean-up-screen-2

  • Now you will see one step being added as highlighted

clean-up-screen-3

After clicking Finish, Eclipse will generate serialVersionUID.

like image 44
Shailendra Avatar answered Sep 19 '22 08:09

Shailendra