游.程 2009-05-26 12:11 采纳率: 0%
浏览 333
已采纳

为什么 Java 有临时字段?

Why does Java have transient fields?

转载于:https://stackoverflow.com/questions/910374/why-does-java-have-transient-fields

  • 写回答

13条回答 默认 最新

  • ℡Wang Yan 2009-05-26 12:53
    关注

    The transient keyword in Java is used to indicate that a field should not be part of the serialization (which means saved, like to a file) process.

    From the Java Language Specification, Java SE 7 Edition, Section 8.3.1.3. transient Fields:

    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.

    Here's a GalleryImage class which contains an image and a thumbnail derived from the image:

    class GalleryImage implements Serializable
    {
        private Image image;
        private transient Image thumbnailImage;
    
        private void generateThumbnail()
        {
            // Generate thumbnail.
        }
    
        private void readObject(ObjectInputStream inputStream)
                throws IOException, ClassNotFoundException
        {
            inputStream.defaultReadObject();
            generateThumbnail();
        }    
    }
    

    In this example, the thumbnailImage is a thumbnail image that is generated by invoking the generateThumbnail method.

    The thumbnailImage field is marked as transient, so only the original image is serialized rather than persisting both the original image and the thumbnail image. This means that less storage would be needed to save the serialized object. (Of course, this may or may not be desirable depending on the requirements of the system -- this is just an example.)

    At the time of deserialization, the readObject method is called to perform any operations necessary to restore the state of the object back to the state at which the serialization occurred. Here, the thumbnail needs to be generated, so the readObject method is overridden so that the thumbnail will be generated by calling the generateThumbnail method.

    For additional information, the Discover the secrets of the Java Serialization API article (which was originally available on the Sun Developer Network) has a section which discusses the use of and presents a scenario where the transient keyword is used to prevent serialization of certain fields.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(12条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘