可序列化如何在java中工作? [英] 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?
推荐答案
这个类有一个静态变量,
这个在每个实例中被序列化
存储?
This class has a static variable, will this be serialized in every instance stored?
否。根据 Java Object Serialization Specificaiton :类的默认可序列化字段被定义为非瞬态和非静态字段。
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?
你可以使用 readObject()
方法,如 Serializable <中所述/ code>
API doc。
You can use the readObject()
method for that, as described in the Serializable
API doc.
这篇关于可序列化如何在java中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!