Java:静态瞬态字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4565653/
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 06:59:43  来源:igfitidea点击:

Java: Static transient fields

javaserializationstaticfieldtransient

提问by python dude

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.

我刚刚发现在 Java 中你可以声明一个字段“静态瞬态”——编译器不会抱怨。众所周知,这似乎没有任何用处,因为静态字段未序列化。

But I wonder, is there actually a case where 'static transient' fields are useful?

但我想知道,实际上是否存在“静态瞬态”字段有用的情况?

回答by Peter C

Nope - you said it yourself, static fields aren't serialized.

不 - 你自己说过,静态字段没有序列化。

Kinda weird that the compiler lets you do that though.

编译器允许你这样做有点奇怪。

回答by MC Emperor

In most cases, it is not useful. Static fields are indeed not serialized by the default serializer.

在大多数情况下,它没有用。静态字段确实没有被默认序列化器序列化。

However, statictransientfields can be detected via reflection. If someone writes its own serializer and he wants to also serialize static fields, then he mighttake the transientkeyword in consideration and skip the serialization of that particular field.

但是,statictransient可以通过反射检测场。如果有人编写了自己的序列化程序并且他还想序列化静态字段,那么他可能会考虑transient关键字并跳过该特定字段的序列化。

PS: This answer is posted for the sake of completeness, and is based on Peter Lawrey's comment. Credits to him.

PS:为了完整起见,发布此答案,并基于Peter Lawrey 的评论。归功于他。