类中的瞬态字段可以使用反射获取吗

发布于 2024-08-21 19:17:02 字数 51 浏览 5 评论 0原文

可以使用反射获取类中的瞬态字段吗? (使用 getDeclaredField(..) )

Can a transient field in a class be obtained using reflection? (using getDeclaredField(..))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

苏大泽ㄣ 2024-08-28 19:17:03

transient 表示该字段不会被序列化。该字段仍然由类声明,因此反思是公平的。

transient indicates that the field will not be serialized. The field is still declared by the class, so it is fair game for reflection.

冰之心 2024-08-28 19:17:03

在所有需要序列化的对象中,都有一些不需要序列化的对象。这就是为什么这个对象被标记为关键字瞬态。

Among all the objects that needs to be serialized there are those one that need not to be serialized. That's why this objects are marked with the keyword transient.

旧情勿念 2024-08-28 19:17:03

transient 字段与反射无关。该关键字仅表示在 Java 序列化过程中应跳过某个字段。因此反射可以像访问任何其他字段一样访问瞬态字段。

transient fields have nothing to do with reflection. The keyword only signals that a field should be skipped during Java serialization process. So reflection can access transient fields just like any other fields.

剧终人散尽 2024-08-28 19:17:02

是的,这是一个正常的字段。您可以通过以下方式检查它是否是瞬态的:

Modifier.isTransient(field.getModifiers());

瞬态
Java 编程语言中的关键字,指示字段不是对象的序列化形式的一部分。当对象被序列化时,其瞬态字段的值不包含在序列表示中,而包含其非瞬态字段的值。

因此,没有逻辑上的理由不能通过反射来访问它。 (有时)被忽略的是字段的值,而不是字段本身。

(顺便说一句,是什么阻碍了您尝试调用 getDeclaredField("yourTransientField")?)

Yes, It is a normal field. You can check whether it is transient by:

Modifier.isTransient(field.getModifiers());

transient:
A keyword in the Java programming language that indicates that a field is not part of the serialized form of an object. When an object is serialized, the values of its transient fields are not included in the serial representation, while the values of its non-transient fields are included.

So no logical reason for it not to be accessible by reflection. It's the value of the field that is ignored (sometimes), not the field itself.

(btw, what hindered you from just trying to call getDeclaredField("yourTransientField")?)

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