Is determining what is transient a trial and error?

155 Views Asked by At

Assume I create a class Foo, whose instance variables are instances of different class's. Eg:

class Foo implements Serializable {
   BarA barA;
   BarB barB;
   .
   .
   BarZ barZ;
}

I understand that when I serialize, I need to all the Bar's to be serializable, else I need to mark them as transient. But How to know which one's should be marked as transient ? Is this trail and error ?

3

There are 3 best solutions below

0
On

You should make sure that all fields that decide the state of your Foo object are serializable, the rest can be transient.

Noone can answer which fields belong to which category but you, the developer.

1
On

I understand that when I serialize, I need to all the Bar's to be serializable, else I need to mark them as transient.

Your understanding is incorrect.

Flagging a field as transient causes it to not be stored when an object is serialized. As such, you should only do this for fields whose values are fundamentally impossible to serialize (e.g, a network connection), or fields whose values can be discarded and recreated later (e.g, a cache, or a reference to an application global). Otherwise, the serialized representation of this object will be incomplete.

While it is often the case that a non-serializable object will associated with a transient field, this is not always the case. Understand what "transient" means before you go throwing it around just to make your code run!

1
On

Even if you are using an external library with no source code and obfuscation, you can write code that using reflection will tell you if it or one of its parent classes and interfaces implements Serializeable. So there cannot be a situation in which you design code and don't know what you are using.