XStream序列化和反序列化中的多态性

编程入门 行业动态 更新时间:2024-10-23 18:24:38
本文介绍了XStream序列化和反序列化中的多态性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这些课程:

@XStreamAlias("person") public class PersonConfig { private AnimalConfig animalConfig; } public interface AnimalConfig {} @XStreamAlias("dog"); public class DogConfig extend AnimalConfig {} @XStreamAlias("cat"); public class CatConfig extend AnimalConfig {}

我希望能够反序列化这个包含上述类的xml:

And I would like to be able to deserialize this xml with the classes above:

<person> <dog/> <person>

除了反序列化这个xml,使用相同的类:

As well as deserialize this xml too, with the same classes:

<person> <cat/> <person>

因此,在这两种情况下, PersonConfig 字段 animalConfig 已填写。在带有 DogConfig 实例的第一个XML中,在带有 CatConfig 实例的第二个XML中。

So that in both cases, the PersonConfig's field animalConfig is filled. In the first XML with a DogConfig instance and in the second XML with a CatConfig instance.

这是否可以通过添加一些注释来实现这个功能?

Is this possible by adding some annotation to make this work?

推荐答案

看来XStream确实如此不允许你轻易做到。

It seems XStream does not allow you to do it easily.

你的问题类似于这个,要求使用XStream管理类似xsd:choice的内容。

Your question is similar to this one, asking for managing something like a xsd:choice with XStream.

如果你不一定需要使用XStream,JAXB将允许您轻松完成:

If you don't necessarily need to use XStream, JAXB will allow you to do it easily :

@XmlRootElement(name="person") public class PersonConfig { private AnimalConfig animalConfig; @XmlElementRefs({ @XmlElementRef(name="cat", type=CatConfig.class), @XmlElementRef(name="dog", type=DogConfig.class) }) public AnimalConfig getAnimalConfig() { return animalConfig; } public void setAnimalConfig(AnimalConfig animalConfig) { this.animalConfig = animalConfig; } }

经过一些研究,列出了您房产的所有可用类别如果您选择使用 XmlAdapter ,则可以避免。 在Blaise Doughan链接中,该示例使用抽象类,而不是接口。

After some researches, listing all available classes for your property can be avoided if you choose to use the XmlAdapter. In Blaise Doughan link, the example uses an abstract class, not an interface.

编辑:

正如Blaise Doughan在评论中所说, @XmlElementRef 更适合此目的。代码已相应更新。

As Blaise Doughan said in its comment, @XmlElementRef is better suited for this purpose. Code has been updated accordingly.

更多推荐

XStream序列化和反序列化中的多态性

本文发布于:2023-08-04 06:00:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293587.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:序列化   多态性   XStream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!