简体   繁体   English

类层次结构的JAXB注释

[英]JAXB annotation for class hierarchy

Hey, I have 2 classes. 嘿,我有两节课。 When I'm trying to create an XML structure from them, I only get the root element (A). 当我尝试从它们创建XML结构时,我只获得根元素(A)。 Why? 为什么? Am I using wrong annotations? 我使用了错误的注释吗?

@XmlRootElement(name = "a")
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class A{
    @XmlElement
    int a;

    protected A(){
    }
 }

@XmlAccessorType(XmlAccessType.FIELD)
public class B extends A{
    @XmlElement
    int b;

    protected B(){
    }
}    

You probably need to use @XmlSeeAlso annotation in your top class: 您可能需要在顶级类中使用@XmlSeeAlso注释:

@XmlSeeAlso(B.class)
@XmlRootElement(name = "a")
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class A{

I wrote 'probably', because it depends on how do you set up your JAXB context. 我写'可能',因为它取决于你如何设置你的JAXB上下文。 Basically you need to make sure all the classes which are supposed to be serialized are known to JAXB. 基本上,您需要确保JAXB知道所有应该序列化的类。 If your B class is not mentioned anywhere else (eg as a property type of one of classes which are already known to JAXB), then JAXB has no chance to know how to serialize instances of B . 如果你的B类没有在其他任何地方被提及(例如,作为JAXB已知的类之一的属性类型),那么JAXB就没有机会知道如何序列化B实例。 The intention of @XmlSeeAlso annotation is to make sure JAXB looks into these listed classes too. @XmlSeeAlso注释的目的是确保JAXB也查看这些列出的类。

UPDATE: 更新:

Alternatively you can provide the list of all the subclasses when creating the JAXBContext object using JAXBContext.newInstance(Class...) , eg: 或者,您可以在使用JAXBContext.newInstance(Class...)创建JAXBContext对象时提供所有子类的列表,例如:

   JAXBContext.newInstance(A.class, B.class);

instead of 代替

   JAXBContext.newInstance(A.class);

which you probably already do. 你可能已经做过了。

But my opinion this is a worse solution, because it makes you think of related classes every time you use JAXB in your code. 但我认为这是一个更糟糕的解决方案,因为每次在代码中使用JAXB时,它都会让您考虑相关的类。 In the top solution you set the relations once forever. 在顶级解决方案中,您可以永久地设置关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM