狐狸.fox 2009-05-26 12:11 采纳率: 0%
浏览 413
已采纳

为什么 Java 有临时字段?

Why does Java have transient fields?

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

  • 写回答

13条回答 默认 最新

  • bug^君 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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。