講真,下次打死我也不敢隨便改serialVersionUID了


            <h2 class="rich_media_title" id="activity-name">
                
                
                
        講真,下次打死我也不敢隨便改serialVersionUID了
                  </h2>
            <div id="meta_content" class="rich_media_meta_list">
                                                                            
                                    <span class="rich_media_meta rich_media_meta_nickname" id="profileBt">
                  <a id="js_name">
                    碼農沉思錄                      </a>
                  <div id="js_profile_qrcode" class="profile_container" style="display:none;">
                      <div class="profile_inner">
                          <strong class="profile_nickname">碼農沉思錄</strong>
                          <img class="profile_avatar" id="js_profile_qrcode_img" src="" alt="">

                          <p class="profile_meta">
                          <label class="profile_meta_label">微信號</label>
                          <span class="profile_meta_value">code-thinker</span>
                          </p>

                          <p class="profile_meta">
                          <label class="profile_meta_label">功能介紹</label>
                          <span class="profile_meta_value">筆者為國內某知名企業不知名碼農,專注Java Web領域多年,有豐富的bug開發經驗。</span>
                          </p>
                          
                      </div>
                      <span class="profile_arrow_wrp" id="js_profile_arrow_wrp">
                          <i class="profile_arrow arrow_out"></i>
                          <i class="profile_arrow arrow_in"></i>
                      </span>
                  </div>
                </span>


                <em id="publish_time" class="rich_media_meta rich_media_meta_text">3天前</em>





            </div>

            
            
                            
            
            
            
                                            
                                                            
                            
            
            <div class="rich_media_content " id="js_content">
                

                

                
                
                <p style="font-family: -apple-system-font, BlinkMacSystemFont, 'Helvetica Neue', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei UI', 'Microsoft YaHei', Arial, sans-serif;letter-spacing: 0.544px;white-space: normal;background-color: rgb(255, 255, 255);text-align: right;" data-mpa-powered-by="yiban.io"><span style="color: rgba(0, 0, 0, 0.65);font-family: 'Monospaced Number', 'Chinese Quote', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;text-align: start;white-space: pre;letter-spacing: 1.4px;font-size: 12px;"></span></p><p style="text-align: center;"><img class="rich_pages " data-ratio="0.666" data-s="300,640" data-src="https://mmbiz.qpic.cn/mmbiz_jpg/XA3sPCPib1l5P34dAsQQPqibib8tyCUCMnwX6RXYICMHYibO8b56dpM8cuHhew6LceId2PJiaEbdsKDZ4Eggzur5UyA/640?wx_fmt=jpeg" data-type="jpeg" data-w="500" style="width: 500px !important; height: auto !important; visibility: visible !important;" _width="500px" src="" crossorigin="anonymous" data-fail="0"></p><section class="code-snippet__fix code-snippet__js"><pre class="code-snippet__js" data-lang="javascript"><code class="hljs"><span class="code-snippet_outer">來源:Java成長路</span></code><code class="hljs less"><span class="code-snippet_outer">鏈接:<span class="hljs-attribute"><span class="hljs-attribute">https</span></span>:<span class="code-snippet__comment"><span class="hljs-comment"><span class="hljs-comment">//www.jianshu.com/p/a4508a8f2420</span></span></span></span></code></pre></section><section style="font-size: 14px;letter-spacing: 1.4px;white-space: normal;line-height: 2em;margin: 1.5em 5px !important;">序列化是一種對象持久化的手段。普遍應用在網絡傳輸、RMI等場景中。類通過實現 java.io.Serializable 接口以啟用其序列化功能。</section><section style="font-size: 14px;letter-spacing: 1.4px;white-space: normal;line-height: 2em;margin: 1.5em 5px !important;">但是,還有一個知識點並未展開介紹,那就是關於serialVersionUID 。這個字段到底有什么用?如果不設置會怎么樣?為什么《阿里巴巴Java開發手冊》中有以下規定:</section><section style="font-size: 14px;letter-spacing: 1.4px;white-space: normal;line-height: 2em;margin: 1.5em 5px !important;"><img class="" data-ratio="0.1527777777777778" data-type="other" data-w="1080" data-src="https://mmbiz.qpic.cn/mmbiz/CvQa8Yf8vq11tWicgbQ0jTiaGle6Dibibo4ZXozI7y0sxrnbthHA5eZ8qRHia8kegttJeOTzWuEAttacty5mBibQHvuw/640?wx_fmt=other" _width="677px" src="https://img2018.cnblogs.com/blog/1112483/201909/1112483-20190909143819446-485477025.png" crossorigin="anonymous" data-fail="0"></section><section style="font-size: 14px;letter-spacing: 1.4px;white-space: normal;line-height: 2em;margin: 1.5em 5px !important;"><strong style="color: rgb(191, 54, 12);">背景知識</strong></section><section style="font-size: 14px;letter-spacing: 1.4px;white-space: normal;line-height: 2em;margin: 1.5em 5px !important;">在展開本文的介紹之前,先來簡單介紹一些和序列化有關的知識,</section><section style="font-size: 14px;letter-spacing: 1.4px;white-space: normal;line-height: 2em;margin: 1.5em 5px !important;"><strong style="color: rgb(191, 54, 12);">Serializable 和 Externalizable</strong></section><section style="font-size: 14px;letter-spacing: 1.4px;white-space: normal;line-height: 2em;margin: 1.5em 5px !important;">Java類通過實現 java.io.Serializable 接口以啟用其序列化功能。<strong style="color: rgb(191, 54, 12);">未實現此接口的類將無法進行序列化或反序列化。</strong>可序列化類的所有子類型本身都是可序列化的。</section><p style="color: rgb(62, 62, 62);font-family: -apple-system-font, BlinkMacSystemFont, &quot;Helvetica Neue&quot;, &quot;PingFang SC&quot;, &quot;Hiragino Sans GB&quot;, &quot;Microsoft YaHei UI&quot;, &quot;Microsoft YaHei&quot;, Arial, sans-serif;font-size: 16px;white-space: normal;widows: 1;letter-spacing: 0.544px;background-color: rgb(255, 255, 255);text-align: center;"></p><section style="font-size: 14px;letter-spacing: 1.4px;white-space: normal;line-height: 2em;margin: 1.5em 5px !important;">如果讀者看過Serializable的源碼,就會發現,他只是一個空的接口,里面什么東西都沒有。<strong style="color: rgb(191, 54, 12);">Serializable接口沒有方法或字段,僅用於標識可序列化的語義。</strong>但是,如果一個類沒有實現這個接口,想要被序列化的話,就會拋出java.io.NotSerializableException異常。</section><section style="font-size: 14px;letter-spacing: 1.4px;white-space: normal;line-height: 2em;margin: 1.5em 5px !important;">它是怎么保證只有實現了該接口的方法才能進行序列化與反序列化的呢?</section><section style="font-size: 14px;letter-spacing: 1.4px;white-space: normal;line-height: 2em;margin: 1.5em 5px !important;">原因是在執行序列化的過程中,會執行到以下代碼:</section><section style="font-size: 14px;letter-spacing: 1.4px;white-space: normal;line-height: 2em;margin: 1.5em 5px !important;"><img class="" data-ratio="0.5575485799701047" data-type="other" data-w="669" data-src="https://mmbiz.qpic.cn/mmbiz/CvQa8Yf8vq11tWicgbQ0jTiaGle6Dibibo4Zr7iaP8yEwHzfzaicHTBfibGaF3BZbCKiboDanJqzLzuKLxUTeBbcPI8klA/640?wx_fmt=other" _width="669px" src="https://img2018.cnblogs.com/blog/1112483/201909/1112483-20190909145454097-584363508.png

" crossorigin="anonymous" data-fail="0">

在進行序列化操作時,會判斷要被序列化的類是否是Enum、Array和Serializable類型,如果都不是則直接拋出NotSerializableException。
Java中還提供了Externalizable接口,也可以實現它來提供序列化能力。
Externalizable繼承自Serializable,該接口中定義了兩個抽象方法:writeExternal()與readExternal()。
當使用Externalizable接口來進行序列化與反序列化的時候需要開發人員重寫writeExternal()與readExternal()方法。否則所有變量的值都會變成默認值。
transient
transient 關鍵字的作用是控制變量的序列化,在變量聲明前加上該關鍵字,可以阻止該變量被序列化到文件中,在被反序列化后,transient 變量的值被設為初始值,如 int 型的是 0,對象型的是 null。
自定義序列化策略
在序列化過程中,如果被序列化的類中定義了writeObject 和 readObject 方法,虛擬機會試圖調用對象類里的 writeObject 和 readObject 方法,進行用戶自定義的序列化和反序列化。
如果沒有這樣的方法,則默認調用是 ObjectOutputStream 的 defaultWriteObject方法以及 ObjectInputStream 的 defaultReadObject 方法。
用戶自定義的 writeObject 和 readObject 方法可以允許用戶控制序列化的過程,比如可以在序列化的過程中動態改變序列化的數值。
所以,對於一些特殊字段需要定義序列化的策略的時候,可以考慮使用transient修飾,並自己重寫writeObject 和 readObject 方法,如java.util.ArrayList中就有這樣的實現。
以上,就是一些讀者需要掌握和和序列化有關的知識。
我們隨便找幾個Java中實現了序列化接口的類,如String、Integer等,我們可以發現一個細節,那就是這些類除了實現了Serializable外,還定義了一個serialVersionUID
那么,到底什么是serialVersionUID呢?為什么要設置這樣一個字段呢?
什么是serialVersionUID
序列化是將對象的狀態信息轉換為可存儲或傳輸的形式的過程。我們都知道,Java對象是保存在JVM的堆內存中的,也就是說,如果JVM堆不存在了,那么對象也就跟着消失了。
而序列化提供了一種方案,可以讓你在即使JVM停機的情況下也能把對象保存下來的方案。就像我們平時用的U盤一樣。把Java對象序列化成可存儲或傳輸的形式(如二進制流),比如保存在文件中。這樣,當再次需要這個對象的時候,從文件中讀取出二進制流,再從二進制流中反序列化出對象。
虛擬機是否允許反序列化,不僅取決於類路徑和功能代碼是否一致,一個非常重要的一點是兩個類的序列化 ID 是否一致,這個所謂的序列化ID,就是我們在代碼中定義的serialVersionUID。
如果serialVersionUID變了會怎樣
我們舉個例子吧,看看如果serialVersionUID被修改了會發生什么?
我們先執行以上代碼,把一個User1對象寫入到文件中。然后我們修改一下User1類,把serialVersionUID的值改為2L。
然后執行以下代碼,把文件中的對象反序列化出來:
執行結果如下:
java.io.InvalidClassException: com.hollis.User1; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2
可以發現,以上代碼拋出了一個java.io.InvalidClassException,並且指出serialVersionUID不一致。
這是因為,在進行反序列化時,JVM會把傳來的字節流中的serialVersionUID與本地相應實體類的serialVersionUID進行比較,如果相同就認為是一致的,可以進行反序列化,否則就會出現序列化版本不一致的異常,即是InvalidCastException。
這也是《阿里巴巴Java開發手冊》中規定,在兼容性升級中,在修改類的時候,不要修改serialVersionUID的原因。 除非是完全不兼容的兩個版本。所以, serialVersionUID其實是驗證版本一致性的。
如果讀者感興趣,可以把各個版本的JDK代碼都拿出來看一下,那些向下兼容的類的serialVersionUID是沒有變化過的。比如String類的serialVersionUID一直都是-6849794470754667710L。
但是,作者認為,這個規范其實還可以再嚴格一些,那就是規定:
如果一個類實現了Serializable接口,就必須手動添加一個private static final long serialVersionUID變量,並且設置初始值。
為什么要明確定一個serialVersionUID
如果我們沒有在類中明確的定義一個serialVersionUID的話,看看會發生什么。
嘗試修改上面的demo代碼,先使用以下類定義一個對象,該類中不定義serialVersionUID,將其寫入文件。
然后我們修改User1類,向其中增加一個屬性。在嘗試將其從文件中讀取出來,並進行反序列化。
執行結果:
java.io.InvalidClassException: com.hollis.User1; local class incompatible: stream classdesc serialVersionUID = -2986778152837257883, local class serialVersionUID = 7961728318907695402
同樣,拋出了InvalidClassException,並且指出兩個serialVersionUID不同,分別是-2986778152837257883和7961728318907695402。
從這里可以看出,系統自己添加了一個serialVersionUID。
所以,一旦類實現了Serializable,就建議明確的定義一個serialVersionUID。不然在修改類的時候,就會發生異常。
serialVersionUID有兩種顯示的生成方式:
一種是默認的1L,比如:
private static final long serialVersionUID = 1L;
另外一種是根據類名、接口名、成員方法及屬性等來生成一個64位的哈希字段,比如:
private static final long serialVersionUID = xxxxL;
后面這種方式,可以借助IDE生成,后面會介紹。
背后原理
知其然,要知其所以然,我們再來看看源碼,分析一下為什么serialVersionUID改變的時候會拋異常?在沒有明確定義的情況下,默認的serialVersionUID是怎么來的?
為了簡化代碼量,反序列化的調用鏈如下:
在initNonProxy中 ,關鍵代碼如下:
在反序列化過程中,對serialVersionUID做了比較,如果發現不相等,則直接拋出異常。
深入看一下getSerialVersionUID方法:
在沒有定義serialVersionUID的時候,會調用computeDefaultSUID 方法,生成一個默認的serialVersionUID。
這也就找到了以上兩個問題的根源,其實是代碼中做了嚴格的校驗,並且在未定義的時候自動生成了一個serialVersionUID。
IDEA提示
為了確保我們不會忘記定義serialVersionUID,可以調節一下Intellij IDEA的配置,在實現Serializable接口后,如果沒定義serialVersionUID的話,IDEA(eclipse一樣)會進行提示:
並且可以一鍵生成一個:
當然,這個配置並不是默認生效的,需要手動到IDEA中設置一下:
在圖中標號3的地方(Serializable class without serialVersionUID的配置),打上勾,保存即可。
總結
serialVersionUID是用來驗證版本一致性的。所以 在做兼容性升級的時候,不要改變類中serialVersionUID的值。
特別說明一下,由於本文標題並不完全能表達本文的全部內容,這里再強調一下:serialVersionUID 既然是驗證版本一致性的,在做版本升級的時候(非兼容性升級),記得要修改這個字段的值哦,這樣可以避免序列化混亂。
如果一個類實現了Serializable接口,一定要記得定義serialVersionUID,否則會發生異常。可以在IDE中通過設置,讓他幫忙提示,並且可以一鍵快速生成一個serialVersionUID。
之所以會發生異常,是因為反序列化過程中做了校驗,並且如果沒有明確定義的話,會根據類名及屬性等自動生成一個。


            <div class="read-more__area" id="js_more_read_area" style="display:none;">
                
            </div>

            
                            <div class="reward_area tc reward_area_primary" id="js_preview_reward_author" style="display:none;">
           
                
                               


                        </div>


免責聲明!

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



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