Java serialVersionUID作用和生成


序列化和反序列化
Java是面向對象的語言,與其他語言進行交互(比如與前端js進行http通信),需要把對象轉化成一種通用的格式比如json(前端顯然不認識Java對象),從對象到json字符串的轉換,就是序列化的過程,反過來,從json字符串轉換成Java對象,就是反序列化的過程。

serialVersionUID是什么
反序列化的過程,需要從一個json字符串生成一個Java對象。典型的如下:

Gson gson = new Gson();
Request req = gson.fromJson("request string", Request.class)


這時候會有問題,需要驗證輸入的json字符串是否是從當前的Request這個類序列化過去的,serialVersionUID就是用來干這個的。當序列化的時候的serialVersionUID與反序列化的時候的serialVersionUID不一致的時候,會跑出InvalidCalssException。
如果沒有顯式地定義一個serialVersionUID,那么Java會默認根據類信息計算一個serivalVersionUID出來。

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender’s class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named “serialVersionUID” that must be static, final, and of type long: 
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L; 
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class–serialVersionUID fields are not useful as inherited members.

 

如何生成
Intellij IDEA可以自動為serializable的類生成一個serialVersionUID。
Preferences - Inspection - Serializable class without ‘serialVersionUID’ 勾選。

這樣,如果沒有申明serialVersionUID屬性,編輯器就會給出提示,按alt + Enter 可以快速生成。

 

這樣在沒有serialVersionUID的類中,可以自動根據提示生成serialVersionUID了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM