问题
I have following use-case for marshalling a POJO to XML using Eclipselink MOXy 2.3:
public abstract class A {
public abstract getX();
}
public class B extends A {
private Foo x;
@Override
public Foo getX() {
return this.x;
}
}
public class C extends B {
// Various fields and properties here
}
I need to marshal B and C but not A. So i set A to be transient which makes B inherit all its members that will be marshalled when marshalling B. I cant set B to be transient since i need to marshal it by itself, but when i marshal C, i need property B.getX() to be marshalled as well.
Is there any way other than @Override
getX() in C to have it marshalled? At the moment it is just one property for which i need to do this, but imagine a large B class with many members, which one would need to @Override
in C to marshal them together with C.
Is there any annotation or possibility in the external mapping file to mark a property in a superclass to be inherited by its immediate subclass (or all subclasses)?
What is the Eclipselink/JAXB way to go here?
Regards,
回答1:
There is nothing special you need to do:
B
I have modified the B
class based on one of your previous questions in order to populate the x
property:
package forum8739246;
public class B extends A {
private Foo x;
public B() {
x = new Foo();
}
public Foo getX() {
return this.x;
}
}
oxm.xml
Below is the metadata file that I based on your comments to my original answer.
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
version="2.3"
package-name="forum8739246">
<java-types>
<java-type name="B" xml-accessor-type="FIELD">
<java-attributes>
<xml-element java-attribute="x" name="X"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
Demo
package forum8739246;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.*;
import javax.xml.namespace.QName;
import org.eclipse.persistence.jaxb.JAXBContextFactory;
public class Demo {
public static void main(String[] args) throws Exception {
Map<String, Object> properties = new HashMap<String, Object>(1);
properties.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "forum8739246/oxm.xml");
JAXBContext jc = JAXBContext.newInstance(new Class[] {C.class},properties);
System.out.println(jc.getClass());
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
JAXBElement<B> b = new JAXBElement<B>(new QName("b"), B.class, new B());
marshaller.marshal(b, System.out);
JAXBElement<C> c = new JAXBElement<C>(new QName("c"), C.class, new C());
marshaller.marshal(c, System.out);
}
}
Output
As can be seen from the output the x property is marshalled for both instances of B
and C
:
class org.eclipse.persistence.jaxb.JAXBContext
<?xml version="1.0" encoding="UTF-8"?>
<b>
<X/>
</b>
<?xml version="1.0" encoding="UTF-8"?>
<c>
<X/>
</c>
来源:https://stackoverflow.com/questions/8739246/jaxb-eclipselink-inherited-properties