java 瞬态变量有什么用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5960280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:40:54  来源:igfitidea点击:

What is the use of transient variables?

javaserializationtransient

提问by muralidhar

Possible Duplicate:
Why does Java have transient variables?

可能的重复:
为什么 Java 有瞬态变量?

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?

瞬态关键字将用于防止特定变量的序列化。但是为什么我们不应该序列化数据呢?有没有内在的安全感?

回答by Joachim Sauer

Some classes are inherently not serializable, because they represent resources outside of the manage Java environment. For example a FileOutputStreamcan'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".

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

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 transientis 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.

使用的另一个原因transient是当您的类进行某种内部缓存时。例如,如果您的类可以进行计算并且出于性能原因它缓存每个计算的结果,那么保存该缓存可能是不可取的(因为重新计算它可能比恢复它更快,或者因为旧的缓存值不太可能是任何用途)。在这种情况下,您会将缓存字段标记为瞬态。

回答by Kaj

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 :)

是的,它可能与安全有关,但原因也可能是该字段中的数据来自其他字段,在这种情况下没有理由发送它。如果可以,请节省带宽:)

回答by Umesh K

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.

如果您不想序列化任何变量/字段,请将其标记为瞬态。银行余额、信用卡详细信息等,如果我们序列化,那么有人可以反序列化并使用它。

回答by ponds

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

在这样的场景中瞬态会有所帮助