简体   繁体   English

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? 这个类有一个静态变量,这会在每个实例中被序列化存储吗?

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." 根据Java Object Serialization Specificaiton :“类的默认可序列化字段被定义为非瞬态和非静态字段。”

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. 您可以使用readObject()方法,如Serializable API doc中所述。

static and transient fields are not serialized. 静态和瞬态字段未序列化。 No, the constructor is not called. 不,没有调用构造函数。 For more details, please check this out: http://java.sun.com/developer/technicalArticles/ALT/serialization/ 有关详细信息,请查看: http//java.sun.com/developer/technicalArticles/ALT/serialization/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM