What is the use of transient variables? [duplicate]

本小妞迷上赌 提交于 2019-12-03 21:56:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!