Why does Java have transient fields?

前端 未结 15 1953
旧时难觅i
旧时难觅i 2020-11-22 03:54

Why does Java have transient fields?

15条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 04:43

    My small contribution :

    What is a transient field?
    Basically, any field modified with the transient keyword is a transient field.

    Why are transient fields needed in Java?
    The transient keyword gives you some control over the serialization process and allows you to exclude some object properties from this process. The serialization process is used to persist Java objects, mostly so that their states can be preserved while they are transferred or inactive. Sometimes, it makes sense not to serialize certain attributes of an object.

    Which fields should you mark transient?
    Now we know the purpose of the transient keyword and transient fields, it's important to know which fields to mark transient. Static fields aren't serialized either, so the corresponding keyword would also do the trick. But this might ruin your class design; this is where the transient keyword comes to the rescue. I try not to allow fields whose values can be derived from others to be serialized, so I mark them transient. If you have a field called interest whose value can be calculated from other fields (principal, rate & time), there is no need to serialize it.

    Another good example is with article word counts. If you are saving an entire article, there's really no need to save the word count, because it can be computed when article gets "deserialized." Or think about loggers; Logger instances almost never need to be serialized, so they can be made transient.

提交回复
热议问题