All our swing projects use this class to serialize settings into XML, back and forth. It is quite convenient but if we create an annotation for this, it would be even better because we can automate the load/save code. Here is the proposal:
This save the variable x into xml call <classname-x>
@save
public int x;
This save the variable into xml call <my_x>
@save(name=my_x)
public int x;
The xml by default call “setting.xml”, unless specify
@save(name=my_x, file=mySetting.xml)
public int x;
package hk.quantr.qemulogpanel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.commons.io.IOUtils;
import com.thoughtworks.xstream.XStream;
import java.io.FileNotFoundException;
public class Setting {
private static Setting setting = null;
public static File file = new File("setting.xml");
public int x;
public int y;
public int width;
public int height;
public int dividerLocation;
public String compareDialog_from;
public String compareDialog_to;
public String compareDialog_limit;
public String compareDialog_qemu;
public String compareDialog_quantr;
public Setting() {
width = 800;
height = 600;
}
public static Setting getInstance() {
if (setting == null) {
setting = load();
}
return setting;
}
public void save() {
XStream xstream = new XStream();
xstream.alias("Setting", Setting.class);
String xml = xstream.toXML(this);
try {
IOUtils.write(xml, new FileOutputStream(file));
} catch (Exception e) {
e.printStackTrace();
}
}
public static Setting load() {
try {
XStream xstream = new XStream();
xstream.allowTypes(new Class[]{Setting.class});
xstream.alias("Setting", Setting.class);
Setting s = (Setting) xstream.fromXML(new FileInputStream(file));
return s;
} catch (FileNotFoundException ex) {
ex.printStackTrace();
file.delete();
setting = new Setting();
setting.save();
return setting;
}
}
}