I have class 'Settings' which stores my app's settings in static variables (to be "visible" from anywhere in app) and I would like to have functionality of saving/loading it.
simplified Settings class:
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Settings {
@XmlElement
private static int option = 0;
private Settings() {
}
public static int getOption() {
return option;
}
public static void setOption(int option) {
Settings.option = option;
}
}
Code used to marshal:
public static void main(String[] args) throws JAXBException {
JAXBContext context = JAXBContext.newInstance(Settings.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(new Settings(), new File("c:\\test\\test.xml"));
}
And output xml:
**Now the problem:** when I change value of *static int option* by calling Settings.setOption(5); as shown below and do unmarshal of the previously marshaled option (which was 0), the resulting Settings object has **value of Settings.option same as the current Settings.option**, which is 5.
Settings.setOption(5);
JAXBContext context = JAXBContext.newInstance(Settings.class);
Settings s2 = (Settings)context.createUnmarshaller().unmarshal(new File("c:\\test\\test.xml"));
// Settings.option is 5, but should be 0!
I just hoped that after unmarshalling it would actually set all static variables of Setting to match with new created object "by nature", but it seems not.
Is there any way to achieve such behavior while preserving static variables? Or am I completely wrong about method of doing save/load of app settings? Please, help :)
以上就是JAXB Is there some way to unmarshal static variables?的详细内容,更多请关注web前端其它相关文章!