最佳实践:Java/XML 序列化:如何确定要反序列化到哪个类?
我有一个将其上下文保存为 XML 的应用程序。在此应用程序中,有一个类层次结构,所有类都实现一个公共接口,并代表不同的设置。例如,第一个设置类可以由 4 个公共浮点字段组成,另一个设置类可以由单个 HashMap 组成。
我试图确定以通用方式处理 XML 写入和读取的最佳方法是什么。例如,我在这个网站上阅读了很多有关 JAXB 和 XStream 的内容,它们能够从 XML 生成特定的类实例。
然而,我的问题与实际类可以是实现给定接口的任何类这一事实有关。当您读取 XML 文件时,您如何从 XML 数据中猜测要实例化的实际类?您如何在应用程序中做到这一点?
我认为我可以在 XML 属性中写入 .class 名称,读取它并将其与所有可能的类 .class 名称进行比较,直到找到匹配项。有没有更明智的方法呢?
谢谢
I have an application that saves its context to XML. In this application, there is a hierarchy of classes, that all implement a common interface, and that represent different settings. For instance, a first setting class may be made of 4 public float fields, another one can be made of a sole HashMap.
I am trying to determine what is the best way to handle writing and reading to XML in a generic way. I read on this site a lot about JAXB and XStream for instance, which are able to make a specific class instance from XML.
However my question is related to the fact that the actual class can be anything that implement a given interface. When you read the XML file, how would you guess the actual class to instantiate from the XML data? How do you do that in your applications?
I thought that I could write the .class name in a XML attribute, read it and compare it to all possible class .class names, until I find a match. Is there a more sensible way?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
xstream 应该已经处理好这个问题并创建正确类型的对象。
教程似乎证实了这一点:
如果您不知道类型,则必须首先将其分配给公共接口类型:
xstream
should already take care of this and create the object of correct type.The tutorial seems to confirm that:
If you don't know the type, you will have to first assign it to the common interface type:
就我而言,我只有一种标头,用于存储序列化的类名,当反序列化它时,我只需使用标头值来确定我应将值反序列化到哪个类。
In my case I just have a kind of header that stores the class name that is serialized and when de-serializing it I just use the header value to figure out to which class shall I de-serialize the values.
最佳实践是使用已建立的、记录良好的 XML 解析器/映射器。所有序列化/反序列化工作都已完成,因此您可以担心业务逻辑。 Castor 和 Apache Axiom 是我用来编组/解组(序列化/反序列化)Java 类和 XML 的两个 API。
http://www.castor.org
Apache Axiom
A best practice would to use an established, well documented XML parser/mapper. All of the serialization/deserialization work has been done, so you can worry about your business logic instead. Castor and Apache Axiom are two APIs that I have used to marshal/unmarshall(serialize/deserialize) Java Classes and XML.
http://www.castor.org
Apache Axiom