本文来自 石锋强 的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 这篇文章。

10-06 21:42