Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

java - Are static variables serialized in Serialization process

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

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

1 Reply

0 votes
by (71.8m points)
  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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...