Why does Java have transient fields?

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

Why does Java have transient fields?

相关标签:
15条回答
  • 2020-11-22 04:45

    To allow you to define variables that you don't want to serialize.

    In an object you may have information that you don't want to serialize/persist (perhaps a reference to a parent factory object), or perhaps it doesn't make sense to serialize. Marking these as 'transient' means the serialization mechanism will ignore these fields.

    0 讨论(0)
  • 2020-11-22 04:48

    Before I respond to this question, I must explain to you the SERIALIZATION, because if you understand what it means serialization in science computer you can easily understand this keyword.

    Serialization When an object is transferred through the network / saved on physical media(file,...), the object must be "serialized". Serialization converts byte status object series. These bytes are sent on the network/saved and the object is re-created from these bytes.
    Example

    public class Foo implements Serializable 
    {
     private String attr1;
     private String attr2;
     ...
    }
    

    Now IF YOU WANT TO do NOT TRANSFERT/SAVED field of this object SO, you can use keyword transient

    private transient attr2;
    

    Example

    0 讨论(0)
  • 2020-11-22 04:52

    Because not all variables are of a serializable nature

    0 讨论(0)
提交回复
热议问题