Search code examples
javavariablesserialization

Do all variables in a serialized class become part of the serialization process in Java?


[enter image description here][1]

[1]: https://i.sstatic.net/Bk99T.pngstrong text

In addition, does it matter whether the variables being part of the serialization process are instance variables or variables in conductors in methods or object variables?


Solution

  • Serialization with the marker interface you mentioned is a tough topic in Java. All member fields of an object will get serialized, except the ones marked with the keyword transient. Other variables like local variables or parameters to constructors or methods are not serialized.

    It is easy to corrupt a Java program by deserializing malicious or corrupted data. You can customize, what will be serialized by implementing the methods private void readObject(ObjectInputStream s) and private void writeObject(ObjectOutputStream s)

    As you can see, those private (!) methods are not members of the interface Serializable, so it's compiler magic that calls them for serialization. If you do not implement them, there is a default implementation.

    Don't forget to specify the variable

    private static final long serialVersionUID = 1L; and give it a new value for each update of your member fields - this will prevent that you deserialize data from another version of your class where the data does not suite the implementation.

    In general: If you really have to use serialization, I would recommend that you read more articles on it, e.g. https://ahdak.github.io/blog/effective-java-part-11/ - it summarizes from the book "Effective Java" by Josh Bloch.

    Also the Java Object Serialization Specification could be interesting for you.