How is serializable work in java?

If I have an instance of the class that I store in the session, I need to make it serializable. This class has a static variable, will it be serialized in every saved instance?

A static variable is a reference to a cache containing a lot of data in the background. Will all this data be serialized? If so, it seems preferable to make this variable transient and re-extract the cache instance each time the instance is restored. It may not be possible to store the cache instance at all in the class.

Will the constructor execute when restoring a class from a serialized state? if not, is there any other method that I can use to reset the transition variable?

+5
source share
2 answers

This class has a static variable, will it have to be serialized in each case stored?

No. According to the Java Serialization Specificaiton : "By default, class-validated fields of a class are defined as non-transient and non-static fields."

Will the constructor execute when restoring a class from a serialized state?

No. Deserialization bypasses the constructors (unless you have a non-serializable superclass).

If not, is there any other method that can be used to reset the transition variable?

To do this, you can use the method readObject()as described in the SerializableAPI.

+11

All Articles