Is Java SerialVersionUid of 1L ok? Or does it need to be unique?

守給你的承諾、 提交于 2019-12-13 13:15:11

问题


I have two java classes which implement Serializable. I set both of them to have a serialVersionUid of 1L.

A coworker said that all classes must have a unique serial version uid and that the jvm will treat classes as equal if they have the same serial version uid. I thought equality was based on the result of the equals method and not the serial version uid.

It was my understanding that the serial version uid was used to indicate the version of the class and that when the class changed in an incompatible fashion that the serial verison uid should be incremented.

Is that correct? Is it okay to use a serialversion uid of 1? Or should java classes never have a serialversion uid of 1L?


回答1:


The class name is part of the serialized representation of an object. The serialVersionUID is only used for versioning the classes. So 1L is a valid value.

Note that if you don't plan to maintain the compatibility of serialization while evolving the class, serialVersionUID is useless, and you can just omit it. Having a serialVersionUID is useful when you want to make compatible changes to a class and still be able to read objects that were serialized using an older version of the class (or vice-versa). But that requires extreme care, and is far from being an easy task. You should generally avoid using serialization for long-term storage. If used for networking purpose, using the same exact classes for the client and the server (i.e. deploying both at once) is the easiest strategy.

Also note that you could easily prove your coworker that he's wrong by simply serializing and deserializing two objects of two different classes having both the same value (1L) as serialVersionUID. If his theory was true, the JVM would have no way of knowing how to deserialize the objects.



来源:https://stackoverflow.com/questions/30716967/is-java-serialversionuid-of-1l-ok-or-does-it-need-to-be-unique

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!