怎么样?
家长班
我们将使用XmlAccessType.NONE告诉JAXB仅映射了显式注释的字段/属性.
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
@XmlAccessorType(XmlAccessType.NONE)
public class Parent {
private String parentProperty1;
private String parentProperty2;
public String getParentProperty1() {
return parentProperty1;
}
public void setParentProperty1(String parentProperty1) {
this.parentProperty1 = parentProperty1;
}
public String getParentProperty2() {
return parentProperty2;
}
public void setParentProperty2(String parentProperty2) {
this.parentProperty2 = parentProperty2;
}
}
儿童班
我们将在子级上使用XmlAccessType.PROPERTY.我们要包括的父类中的任何属性都将被覆盖并显式注释.在此示例中,我们将从Parent类中引入parentProperty2.您只需要覆盖父类中的getter.
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
public class Child extends Parent {
private String childProperty;
@Override
@XmlElement
public String getParentProperty2() {
return super.getParentProperty2();
}
public String getChildProperty() {
return childProperty;
}
public void setChildProperty(String childProperty) {
this.childProperty = childProperty;
}
}
示范课
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Child.class);
Child child = new Child();
child.setParentProperty1("parentProperty1");
child.setParentProperty2("parentProperty2");
child.setChildProperty("childProperty");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(child, System.out);
}
}
输出量
childProperty
parentProperty2