RoyalTiger RoyalTiger - 2 months ago 10
Java Question

Can a transient variable be serialized in any way?

I faced this question in an interview. Please help me to find the answer. The question was Can a transient variable be serialized in any way?

Answer

static and transient fields are not serialized by default.

However they can be serialized if

  • the same object is accessible via a serialized field.
  • the object is serialized in a readObject/writeObject or readExternalizable/writeExternalizable.
  • you are using a different serialization library with different rules (I don't know any which serializes static fields, though I have written such a library by mistake once)

Usually a field is made transient to mean it shouldn't be serialized, though sometimes it might be because

  • the type is not Serializable
  • you don't want to use the default Serialization.
Comments