MOXY中的JAXBinheritance

我有两节课:

package a; class A { private  fieldOfClassA; // getters, and setters } package b; class B extends A{ private  fieldOfClassB; // getters, and setters } 

我想将类B编组为xml元素,并从类A添加属性fieldOfClassB和fieldOfClassA,但它在编组期间打印以下警告消息:

 Ignoring attribute [fieldOfClassA] on class [bB] as no Property was generated for it. 

请注意,这两个类来自两个不同的包,我无法更改此对象模型。

先感谢您!

编辑:

我正在使用外部绑定文件。

从您发布的日志消息中,我可以看到您正在使用MOXy的外部映射文档(请参阅http://blog.bdoughan.com/2010/12/extending-jaxb-representing-annotations.html )。 映射inheritance属性有两种不同的方法。


选项#1 – 映射属于父项的inheritance属性

默认情况下,字段/属性需要在其所属的类中进行映射。 由于MOXy在包级别范围内定义外部映射文档,因此您需要单独的AB映射文档。

forum10874711 /一个/ binding1.xml

           

forum10874711 / B / binding1.xml

            

forum10874711 / B / jaxb.properties

要将MOXy指定为JAXB实现,您需要在与域模型相同的包中添加名为jaxb.properties的文件,并使用以下条目。

 javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory 

演示

 package forum10874711; import java.util.*; import javax.xml.bind.*; import org.eclipse.persistence.jaxb.JAXBContextFactory; import forum10874711.bB; public class Demo1 { public static void main(String[] args) throws Exception { Map properties = new HashMap(1); List metadata = new ArrayList(2); metadata.add("forum10874711/a/binding1.xml"); metadata.add("forum10874711/b/binding1.xml"); properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadata); JAXBContext jc = JAXBContext.newInstance(new Class[] {B.class}, properties); B b = new B(); b.setFieldOfClassA("foo"); b.setFieldOfClassB(123); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(b, System.out); } } 

产量

   foo 123  

选项#2 – 映射属于Child的inheritance属性

父类A' can be marked @XmlTransient, this will allow us to map the inherited fields/properties on the child class B` this will allow us to map the inherited fields/properties on the child class (请参阅http://blog.bdoughan.com/2011/06/ignoring-inheritance-with-xmltransient .html )。

forum10874711 /一个/ binding2.xml

       

forum10874711 / B / binding2.xml

             

演示

 package forum10874711; import java.util.*; import javax.xml.bind.*; import org.eclipse.persistence.jaxb.JAXBContextFactory; import forum10874711.bB; public class Demo2 { public static void main(String[] args) throws Exception { Map properties = new HashMap(1); List metadata = new ArrayList(2); metadata.add("forum10874711/a/binding2.xml"); metadata.add("forum10874711/b/binding2.xml"); properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, metadata); JAXBContext jc = JAXBContext.newInstance(new Class[] {B.class}, properties); B b = new B(); b.setFieldOfClassA("foo"); b.setFieldOfClassB(123); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(b, System.out); } } 

产量

   foo 123