1

Possible Duplicate:
Why should I bother about serialVersionUID?

I am using a class that implemented Serializable. Eclipse gives me a "No Serial UID" warning, but the writing and reading the class works fine. I was wondering what is the purpose of a Serializable class having a UID? Is it just good practice or will my class not work without it eventually? Can it be any number?

Community
  • 1
  • 1
Flynn
  • 5,903
  • 7
  • 38
  • 55
  • 2
    please read http://stackoverflow.com/questions/285793/why-should-i-bother-about-serialversionuid –  May 22 '12 at 18:46

1 Answers1

5

It is important when you serialize and de-serialize the same class using different VMs or on different machines. The UID is used to check if the class you are trying to de-serialize is the really the one you think it is, so if your class in your code has one UID, and the class that was serialized has a different one, the de-serialization will fail.

A class without a UID will be given one automatically by the JVM, but there is no guarantee that different JVMs will give the same UID to the same class.

Read the javadoc of the Serializable interface for more details.

Can it be any number?

Ideally it should be some number unique to that particular version of your class (like a hash), if you make changes to your class that affect serialized fields (non-transient), the UID needs to change. I think Eclipse can generate a UID automatically for you.

trutheality
  • 23,114
  • 6
  • 54
  • 68
  • 1
    I agree with most of this. As for uniqueness, there's no need for it to be unique among classes, you just need it to be changed if the class changes in an incompatible way. The reason the default version created by the jvm is a hash is so that it is sensitive to class level changes. – jtahlborn May 22 '12 at 18:56
  • @jtahlborn Would there be a problem if you had two different classes with the same UID and you tried to de-serialize one as the other? – trutheality May 22 '12 at 18:59
  • you can't do that with standard java serialization, as the name of the class is part of the serial data. – jtahlborn May 22 '12 at 19:00
  • @jtahlborn edited to uniqueness between versions. – trutheality May 22 '12 at 19:05
  • If you make changes too the non-transient fields *that are serialization-incompatible in the terms of the Object Versioning sction of the Object Serialization Specification* you need to change/implement either the readObject/writeObject/readResolve/writeReplace methods, the serialFields member, or *as a last resort* the serialVersionUID value as a stopper. It is a last resort, and the extent to which Serialization supports class versioning is very widely underestimated. – user207421 May 22 '12 at 22:25
  • Altougth of necessary or not, it is noise information in code, a boilerplate. – Daniel Hári Jun 30 '16 at 15:02