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

前端 未结 8 1987
生来不讨喜
生来不讨喜 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:53

    Yes, I've seen code that defined serialVersionUID like that too. I think it is a bad idea.

    In this context there is only one "distinguished" value for the serialVersionUID field; i.e. zero ... 0L. Zero means "compute the version id at runtime by applying the standard algorithm" based on the actual class that you are serializing / deserializing. That means that whenever your code's effective serialization signature changes, the serialization / deserialization code will use a different version id. From a (big picture) type safety perspective, this is the safest thing to do, though it is also somewhat inefficient, and protentially more fragile.

    What is the meaning?

    The 1L has no special meaning. It is just a number that will match 1L as the "other" version id.

    To my mind, you are better off either using 0L, or a version number that was (at some point) generated using the standard algorithm.

    • If you use 0L, then you get definite deserialization exceptions if classes change in ways that could be source of problems. If you need this, it is a good thing.

    • On the other hand you use a generated version id, you (the programmer) can make your own decision about when to regenerate the id. And when you do decide to regenerate, the id will only change if the class signature has changed. (If classes representation etc hasn't changed, the regenerated signature should be identical to the original one!) And when the id does change, you can think about whether to add custom methods ('readObject', etc) to deal with the incompatibility.

    • However, if you use 1L, you can't tell if the version id needs to change without checking your code history, and comparing the old / new versions of the classes ... back as far as you need to.

    Is that useful?

    It depends on what you consider "useful" to mean. If you think it is a good thing to hard wire the version id to "trust me, it is ok", then 1L is useful.


    My recollection is that some versions of Eclipse offer 1L as one of the possible auto-corrections for a missing serialVersionUID field warning. That is probable where the instances you see have come from.

提交回复
热议问题