Java:静态瞬态字段

发布于 2024-10-09 11:23:26 字数 108 浏览 0 评论 0原文

我刚刚发现在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伴梦长久 2024-10-16 11:23:26

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

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

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

Kinda weird that the compiler lets you do that though.

月下客 2024-10-16 11:23:26

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

然而,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 the transient 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文