问题
Possible Duplicate:
Why does Java have transient variables?
The transient keyword will be used to prevent serialization of a particular variable. But why should we not to serialize the data? Is there any inner security?
回答1:
Some classes are inherently not serializable, because they represent resources outside of the manage Java environment. For example a FileOutputStream
can't really be serialized, because it represents an open file handle. The same is true for a Socket
: you can't save and restore "open sockets".
If you want to serialize some object that has a field of that type, then you'll have to mark those fields as transient.
Another reason to use transient
is when your class does some kind of internal caching. If, for example, your class can do calculations and for performance reasons it caches the result of each calculation, then saving that cache might not be desirable (because recalculating it might be faster than restoring it, or because it's unlikely that old cached values are of any use). In this case you'd mark the caching fields as transient.
回答2:
Yes, it can be security related, but the reason can also be that the data in the field is derived from other fields, and there's no reason to send it in that case. Save bandwidth if you can :)
回答3:
If you dont want to serialize any variable/field mark it as a transient. Bank balance, credit card details etc if we serialize then someone can deserialize it and use it.
回答4:
Consider a class having user name and password as one of its field. Also consider you are passing this object in network after serialization and deserializing it some where else.
In such scenerios transient will be helpful
来源:https://stackoverflow.com/questions/5960280/what-is-the-use-of-transient-variables