1. 程式人生 > >java 中 transient 關鍵字意義

java 中 transient 關鍵字意義

本文來自 石鋒強 的CSDN 部落格 ,全文地址請點選:https://blog.csdn.net/shfqbluestone/article/details/45251627?utm_source=copy

譯文出處:Why does Java have transient variables?
另外推薦一篇文章,我覺得寫得挺好的Java深度歷險(十)——Java物件序列化與RMI
java 中的 transient 關鍵字表明瞭 transient 變數不應該被序列化(transient)。
參考Java Language Specification, Java SE 7 Edition, Section 8.3.1.3. transient Fields:

被 transient 標記的這些變數,表明他們是某個物件中不需要被持久狀態的部分(Variables may be marked transient to indicate that they are 
not part of the persistent state of an object.)。
  •  

例如,你可能有一些欄位是從其他欄位匯出來的,這些欄位的值應該是程式根據一定的演算法自動生成的,而不是通過序列化來持久狀態(For example, you may have fields that are derived from other fields, and should only be done so programmatically, rather than having the state be persisted via serialization.)。

下面是一個相簿 GalleryImage 類,這個相簿類包含一張圖片和由這張圖片匯出的一張縮圖。

class GalleryImage implements Serializable
{
    private Image image;
    private transient Image thumbnailImage;

    private void generateThumbnail()
   {
    // Generate thumbnail.
    // 根據 image 原圖,由相應的演算法來產生縮圖。
   }

   private void readObject(ObjectInputStream inputStream)
        throws IOException, ClassNotFoundException
    {
        inputStream.defaultReadObject();
        generateThumbnail();
    }    
}
  •  

在上面的例子中, thumbnailImage 是通過呼叫 generateThumbnail 方法產生的一張縮圖。

thumbnailImage 欄位被標記為 transient ,所以只有原始圖片 image 欄位被序列化了,縮圖 thumbnailImage 不會被序列化。這意味著儲存被序列化後的物件時需要更少的儲存空間。

在反序列化時,readObject 方法會被呼叫,為了使物件的狀態恢復到被序列化時,readObject 方法會執行所有必要的操作。在這裡, thumbnail 縮圖需要被生成,所以 readObject 被重寫了,所以 thumbnail 縮圖可以通過呼叫 generateThumbnail 方法來生成。

想要了解更多的資訊,可以參考 Discover the secrets of the Java Serialization API 這篇文章。