Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm stumbled upon understanding java serialization. I have read in many documents and books that static and transient variables cannot be serialized in Java. We declare a serialVersionUid as follows.

private static final long serialVersionUID = 1L;

If a static variable was not serialized then, we often face an exception during the de-serialization process.

java.io.InvalidClassException

in which the serialVersionUID from the deserialized object is extracted and compared with the serialVersionUID of the loaded class.

To my knowledge i think that if static variables cannot be serialized. There is no point of that exception. I may be wrong because I'm still learning.

Is it a myth that "Static and transient variables in java cannot be serialized". Please correct me, I'm in a mess about this concept.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
247 views
Welcome To Ask or Share your Answers For Others

1 Answer

  1. Instance Variables: These variables are serialized, so during deserialization we will get back the serialized state.

  2. Static Variables: These variables are not serialized, So during deserialization static variable value will loaded from the class.(Current value will be loaded.)

  3. transient Variables: transient variables are not serialized, so during deserialization those variables will be initialized with corresponding default values (ex: for objects null, int 0).

  4. Super class variables: If super class also implemented Serializable interface then those variables will be serialized, otherwise it won't serialize the super class variables. and while deserializing, JVM will run default constructor in super class and populates the default values. Same thing will happen for all superclasses.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...