在方法中读取 XML 文件时出现 CannotResolveClassException
我正在尝试编写一个类,使我能够只编写 .save();制作儿童班级的永久副本。我创建了一种创建 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();
}
,以及另一个应该读取它的方法:
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);
}
问题是,当我尝试使用 loadFile() 时,我收到 com.thoughtworks.xstream.mapper.CannotResolveClassException。
我检查过谷歌,最接近的结果是 xstream 的不同实例无法通信。
这可以通过将 xstream 移动到类字段来解决,但是随后我收到一些关于 xstream 无法序列化自身的错误。
有没有一种好方法可以在类中实现读取和写入方法,而无需在框外创建 xstream 实例?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您在
save()
中使用别名,因此会将简单类名而不是完全限定的类名写入 XML。这使得loadFile()
无法确定它所引用的类。您可以通过以下两种方法之一解决此问题:
XStream
实例上使用的所有别名,并从save()
和调用该方法>loadFile()
以便它们可以使用同一组别名进行操作。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 makesloadFile()
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 bothsave()
andloadFile()
so that they can operate with the same set of aliases.