简体   繁体   English

为什么我们需要transient关键字来防止序列化? [爪哇]

[英]Why we need transient keyword to prevent serialization? [ Java ]

I do not understand that why we need transient keyword to prevent serialization of a particular data member.我不明白为什么我们需要瞬态关键字来防止特定数据成员的序列化。 We can also make it static because static data member can not be serialized.我们也可以将其设为静态,因为静态数据成员无法序列化。 Please guide me if I am wrong!如果我错了,请指导我!

static does not just make a member not serialized; static不仅使成员未序列化; it also means that there is only one copy of that field for the entire class .这也意味着整个班级只有该字段的一个副本。 If you want there to be a copy of that field for each object, but do not want that object to be serialized, you need transient ;如果您希望每个对象都有该字段的副本,但不希望该对象被序列化,则需要transient static will do something completely different. static会做一些完全不同的事情。

Making variables static without fully understanding this is a massively common source of bugs for new Java developers.对于新的 Java 开发人员来说,在没有完全理解这一点的情况下将变量static是一个非常常见的错误来源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM