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
637 views
in Technique[技术] by (71.8m points)

serialization - how does serializable work in java?

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

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

Will the constructor execute when a class is restored from a serialized state? if not is there any other method I can use to re-instate a transient variable?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This class has a static variable, will this be serialized in every instance stored?

No. According to the Java Object Serialization Specificaiton: "Default serializable fields of a class are defined to be the non-transient and non-static fields."

Will the constructor execute when a class is restored from a serialized state?

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

if not is there any other method I can use to re-instate a transient variable?

You can use the readObject() method for that, as described in the Serializable API doc.


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

...