现在的位置: 首页 > 综合 > 正文

Java学习札记10:Why generate long serialVersionUID instead of a simple 1L?

2018年04月04日 ⁄ 综合 ⁄ 共 2130字 ⁄ 字号 评论关闭




一些答案:

1、

The idea behind using 1L is so that you increment it every time you change the class properties or methods.


2、

The "long" default of the serialVersionUID is the default value as defined by the Java Serialization Specification, calculated from the default serialization behaviour.

So if you add the default version number, your class will (de-)serialize faster as long as nothing has structurally changed, but you'll have to take care that if you change the class (add/remove
fields) you also update the serial number.

If you do not have to be compatible to existing bit streams, you can just put 1L there and increment the version as needed when something changes. That is, when the default serialisation version
of the changed class would be different from the default version of the old class.


3、

There is no runtime performance impact of allowing the serialversionUID to be generated automatically - it's generated at compile
time by javac...if you decompile the class's bytecode, you'll actually see the variable statically in the bytecode.


4、

You absolutely should create a serialVersionUID every time you define a class that implements java.io.Serializable. If you don't, one will be created for you automatically, but this is bad. The
auto-generated serialVersionUID is based on the method signatures of your class, so if you change your class in the future to add a method (for example), deserializing the "old" versions of the class will fail. Here's what can happen:

    1. Create the first version of your class, without defining the serialVersionUID. 

    2. Serialize an instance of your class to a persistent store; a serialVersionUID is automatically generated for you. 

    3. Modify your class to add a new method, and redeploy your application. 

    4. Attempt to deserialize the instance that was serialized in step 2, but now it fails (when it should succeed), because it has a different auto-generated serialVersionUID. 


5、

If you don't specify a serialVersionUID then Java makes one on the fly. The generated serialVersionUID is that number. If you change something in your class that doesn't really make your class incompatible
with previous serialized verisons but changes the hash, then you need to use the generated very-large-number serialVersionUID (or the "expected" number from the error message). Otherwise, if you are keeping track of everything yourself, 1, 2, 3... is better.



问题出处:

http://stackoverflow.com/questions/888335/why-generate-long-serialversionuid-instead-of-a-simple-1l







抱歉!评论已关闭.