Is there a way by which i can store a value of a static variable during Serializaion?
In Java , how do we store开发者_如何学编程 value of a static variable during Serializaion?
The same as any other field.
static String name;
// assign
name = "Bob";
// get
String n = name;
If you want to save it to a file, you can use a shutdown hook to write the data, however this is not guaranteed to run. I would write the data to a file every time it changes and load it on start up.
private static final String NAME_FILE = "name.txt";
static String name; static {
try {
name = FileUtils.readFileToString(NAME_FILE );
} catch (IOException e) {
name = "unknown";
}
public static String getName() { return name; }
public static void setName(String name) {
this.name = name;
try {
FileUtils.writeStringToFile(NAME_FILE, name);
} catch(IOException e) {
log.error(e);
}
}
You can store a variable during serialization by overriding wrireObject/readObject however, this is a bad idea. You are better off serializing the static value instead.
You can't serialize static variables, but you can use only one instance of class instead static. Look to singleton pattern.
I suppose, the question is more about storing the value of a static field between applications startups and shutdowns.
(If this assumption is correct then) you have to store the value manually to some external storage (like a text file) and then you can perform a static initialization:
static String field;
static {
field = readFromFile();
}
UPD: you'll have to override readObject
method and you'll also have to introduce kind of a static flag variable. In readObject
method you'll check the flag and if it's not set to `true' (i.e. if static variables aren't initialized yet), you'll do something like in a code snippet above.
I also suppose that it can be necessary to make some synchronization if you have multiple threads.
A good answer for exactly this question:
"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."
精彩评论