瞬态变量有什么用? [英] What is the use of transient variables?

查看:365
本文介绍了瞬态变量有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么Java有瞬态变量?

transient关键字将用于防止特定变量的序列化。但为什么我们不应该序列化数据呢?是否存在内部安全性?

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?

推荐答案

某些类本身不可序列化,因为它们代表管理Java环境之外的资源。例如, FileOutputStream 无法真正序列化,因为它代表一个打开的文件句柄。对于套接字也是如此:您无法保存和恢复打开套接字。

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.

使用的另一个原因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.

这篇关于瞬态变量有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆