Java:静态瞬态字段
我刚刚发现在 Java 中你可以声明一个字段“静态瞬态”——编译器不会抱怨。这似乎没有任何用处,因为众所周知,静态字段没有序列化。
但我想知道,实际上是否存在“静态瞬态”字段有用的情况?
I just found out in Java you can declare a field 'static transient' - the compiler doesn't complain. This doesn't seem to be useful in any way since static fields are not serialized, as we all know.
But I wonder, is there actually a case where 'static transient' fields are useful?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(2)
不 - 你自己说过,静态字段没有序列化。
不过编译器允许你这样做有点奇怪。
Nope - you said it yourself, static fields aren't serialized.
Kinda weird that the compiler lets you do that though.
在大多数情况下,它没有用。静态字段确实不会被默认序列化器序列化。
然而,
static
transient
字段可以通过反射来检测。如果有人编写自己的序列化程序并且他还想序列化静态字段,那么他可能会考虑使用transient关键字并跳过该特定字段的序列化。PS:这个答案是为了完整性而发布的,并且基于 Peter Lawrey 的评论。归功于他。
In most cases, it is not useful. Static fields are indeed not serialized by the default serializer.
However,
static
transient
fields can be detected via reflection. If someone writes its own serializer and he wants to also serialize static fields, then he might take thetransient
keyword in consideration and skip the serialization of that particular field.PS: This answer is posted for the sake of completeness, and is based on Peter Lawrey's comment. Credits to him.