狐狸.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 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?