I'm trying to write a class that would enable me to just write .save(); to make a permanent copies of child classes. I've created a method that creates the xml:
public boolean save() throws IOException{
XStream xstream = new XStream(new KXml2Driver());
FileWriter extenceWriter = new FileWriter(saveFile);
xstream.alias(this.getClass().getSimpleName(), this.getClass());
xstream.toXML(this, extenceWriter);
return saveFile.exists();
}
and another one that should read it:
public Object loadFile(String path) throws FileNotFoundException{
File file = new File(appRootDIR + File.separator + path);
XStream xstream = new XStream(new KXml2Driver());
FileReader extenceReader = new FileReader(file);
return xstream.fromXML(extenceReader);
}
The problem is that i get a com.thoughtworks.xstream.mapper.CannotResolveClassException when i try to use loadFile().
I've checked google and the closest hit was that different instances of xstream can't communicate.
This could be solved by moving xstream to a class field, but then I get some errors regarding to the matter that xstream can't serialise itself.
Is there a good way to implement both read and write methods in a class without having to create a xstream instance outside of the box?
Because you are using an alias in save()
, the simple class name rather than the fully qualified class name is written to the XML. This makes loadFile()
unable to figure out what class it is referring to.
You can fix this in one of two ways:
XStream
instance, and call that method from both save()
and loadFile()
so that they can operate with the same set of aliases.