有什么方法可以保存“静态成员"的状态? [英] Is there any way by which I can save the state of `static members`?

查看:31
本文介绍了有什么方法可以保存“静态成员"的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像我们使用序列化保存实例变量的方式一样,有什么方法可以保存static成员的状态?

Just like the way we save the instance variables using serialization, is there any way by which I can save the state of static members?

如果有一种情况,需要恢复静态成员的状态来恢复某些东西,人们会怎么做?

If there is a situation, where getting back the state of static members is necessary to restore something, how would one do that?

推荐答案

我想到的最简单的选择是使用 单例 而不是静态字段.单例对象可以被序列化和反序列化,你可以管理它的生命周期,同时你保留静态字段给你的全局状态"(也就是说,全局状态是一件坏事,但这是一个不同的话题)

The easiest option that comes to my mind is to use a singleton rather than static fields. 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)

否则 - 在类加载器的整个生命周期(通常意味着 JVM 的生命周期)中都会保留静态状态.因此,如果您想保持状态,最好在关闭时进行,并在类加载时恢复.

Otherwise - the static state is preserved throughout the lifetime of the classloader (which usually means the lifetime of the JVM). So if you want to persist state, it makes sense to do it on shutdown, and restore it on class load.

  • Runtime.addShutdownHook(..) 在关机时执行序列化
  • 使用 static {..} 块在下次打开时加载它
  • Runtime.addShutdownHook(..) to perform the serialization on shutdown
  • use a static {..} block to load it on next open

序列化格式可以是任何格式.JSON、BSON、java 序列化(使用ObjectOutputStream)

The serialization format can be anything. JSON, BSON, java serialization (using ObjectOutputStream)

但这是不寻常的,而且在大多数情况下是错误的做法.所以请确保这是你想要的.如果您只是希望状态在应用程序的整个生命周期内都存在,请不要做任何事情.如果您想将某些内容保留更长时间,请选择单例选项或考虑使用小型数据库而不是静态字段.

But this is an unusual and in most cases the wrong thing to do. So make sure this is what you want. If you simply want the state to live for the lifetime of the application, don't do anything. And if you want to persist something for longer, either pick the singleton option or consider using a small database rather than static fields.

这篇关于有什么方法可以保存“静态成员"的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆