What means 1L serialVersionUID? When could I use this default value 1L?

前端 未结 8 1983
生来不讨喜
生来不讨喜 2021-02-05 07:02

There are 3 ways to define the serialVersionUID :

1. private static final long serialVersionUID = 1L; (Default)
2. private static final long serialVersionUID = -         


        
8条回答
  •  情歌与酒
    2021-02-05 07:46

    It's important to make clear the fact that having a class implement the Serializable interface makes ALL fields not declared transient part of the exported API of the class, whether or not those fields are declared private.

    In other words, implementing Serializable:

    • breaks encapsulation. If the class has any chance to become a successful, long-lived class then you must support the serialized form ... forever.

    • can seriously impair your ability to evolve that class, precisely because it is a part of its exported API. The alternative is to break backward compatibility.

    • can create security problems for your class and its application. Deserialization represents a way for making Java objects without a constructor, so it's possible to violate a class's invariants by providing rogue byte streams to the deserialization facility.

    The serialVerionUID should be thought of as a property of the serialized form. It is meant to convey to one JVM whether or not there a difference between the serialized form of a class instance that it is receiving and the serialized form of of that same class rendered (maybe) somewhere else.

    You can see the potential problems that may occur if the serialized forms are different but the UIDs are the same. The receiving JVM will assume that the received serial form version between an old class and the new one are the same when they aren't and will dutifully go ahead and attempt to deserialize the byte stream.

    TLDR: You shouldn't change the UID when you feel like it. You should change it when the serialized form of the class changes so that versions of software that use older versions of your class (with the different serialized form) will break instead of (possibly silently) doing the wrong thing. Not designing a good serialized form your classes will make it harder (even much harder) to provide backward compatibility for its clients. In the ideal case, the serialized form for a class persists throughout its entire evolution (and so its UID need never change).

提交回复
热议问题