How does marking a field as transient make it possible to serialise an object

核能气质少年 提交于 2019-11-27 21:25:29

transient doesn't disable serialization altogether; it just marks members that won't be serialized. It's typically used for stuff that would be incorrect or irrelevant when the object is unserialized, or stuff that it'd be less-than-safe to store (passwords, decrypted data, that sort of thing), or non-serializable stuff that could be easily reconstructed.

In this case, i assume the Loan class isn't serializable. (If it were, then A would be correct.) Marking v3 as transient just tells Java not to worry about that field, but go ahead and serialize the others. This means an unserialized Foo might have a null v3. If you want to store the Loan as well, you'd need to either keep track of enough info to recreate it at will, or change class Loan so that it implements java.io.Serializable as well.

Alternatively, there are methods you could implement (writeObject, readObject) if you need control over serialization. But that can be a bit of a hassle.

Then how is transient in this case, helping us to serialize foo?

Because it allows you to serialize the rest of Foo, the other members that are serializable.

First, are you sure that Loan is not serializable? If it is, then B doesn't apply.

On the other hand, if it indeed is not, then B and C are right. transient doesn't turn off serialization generally, but only for the field with which it's associated. Thus, serializing Foo would not transmit a value for the v3 field. On the receiving end, when re-initializing the Foo instance, the serialization mechanism wouldn't try to read that field from the stream, and would leave it null.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!