旧行李 2009-05-26 12:11 采纳率: 25%
浏览 626
已采纳

为什么 Java 有临时字段?

Why does Java have transient fields?

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

  • 写回答

13条回答 默认 最新

  • MAO-EYE 2009-05-26 12:53
    关注

    The transient keyword in Java is used to indicate that a field should not be serialized.

    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 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教