瞬态变量有什么用?
可能的重复:
为什么 Java 有瞬态变量?
瞬态关键字将用于防止序列化的特定变量。但为什么我们不应该序列化数据呢?内心有安全感吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有些类本质上是不可序列化的,因为它们代表管理 Java 环境之外的资源。例如,
FileOutputStream
无法真正序列化,因为它代表一个打开的文件句柄。Socket
也是如此:您无法保存和恢复“打开的套接字”。如果要序列化某个具有该类型字段的对象,则必须将这些字段标记为瞬态。
使用瞬态的另一个原因是当您的类执行某种内部缓存时。例如,如果您的类可以执行计算,并且出于性能原因它缓存每个计算的结果,那么保存该缓存可能并不理想(因为重新计算它可能比恢复它更快,或者因为旧的缓存值不太可能被删除)任何用途)。在这种情况下,您可以将缓存字段标记为瞬态。
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 aSocket
: 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.是的,这可能与安全相关,但原因也可能是该字段中的数据是从其他字段派生的,在这种情况下没有理由发送它。如果可以的话可以节省带宽:)
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 :)
如果您不想序列化任何变量/字段,请将其标记为瞬态。银行余额、信用卡详细信息等,如果我们序列化,那么有人可以反序列化并使用它。
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.
考虑一个将用户名和密码作为其字段之一的类。还要考虑在序列化后在网络中传递该对象并在其他地方反序列化它。
在这种情况下瞬态会有所帮助
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