Is there any way by which I can save the state of `static members`?
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开发者_如何学Python 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)
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(..)
to perform the serialization on shutdown- use a
static {..}
block to load it on next open
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.
精彩评论