繁体   English   中英

有什么方法可以保存“静态成员”的 state 吗?

[英]Is there any way by which I can save the state of `static members`?

就像我们使用序列化保存instance variables的方式一样,有什么方法可以保存static成员的 state 吗?

如果有一种情况,需要取回 static 成员的 state 来恢复某些东西,该怎么做呢?

我想到的最简单的选择是使用singleton而不是 static 字段。 The singleton object can be serialized and deserialized, and you can manage its lifetime, while you preserve the 'global state' that static fields give you (that said, global state is a bad thing, but that's a different topic)

否则 - static state 在类加载器的整个生命周期(通常意味着 JVM 的生命周期)中被保留。 因此,如果您想保留 state,在关机时执行此操作并在 class 负载时恢复它是有意义的。

  • Runtime.addShutdownHook(..)在关机时执行序列化
  • 使用static {..}块在下次打开时加载它

序列化格式可以是任何东西。 JSON, BSON, java 序列化(使用ObjectOutputStream

但这是不寻常的,在大多数情况下是错误的做法。 因此,请确保这是您想要的。 如果您只是希望 state 在应用程序的整个生命周期内都存在,请不要做任何事情。 如果您想保留更长时间,请选择 singleton 选项或考虑使用小型数据库而不是 static 字段。

暂无
暂无

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

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