我正在尝试重现您的问题,但到目前为止还没有成功。你能看出我在哪里做的事情和你不一样吗?以下是我的示例代码:
一个
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public abstract class A {
public abstract C getC();
public abstract void setC(C c);
}
乙
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class B extends A {
private C c;
@Override
public C getC() {
return c;
}
@Override
public void setC(C c) {
this.c = c;
}
}
C
public class C {
}
演示
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import org.eclipse.persistence.Version;
public class Demo {
public static void main(String[] args) throws Exception {
System.out.println(Version.getVersionString());
JAXBContext jc = JAXBContext.newInstance(B.class);
System.out.println(jc);
B b = new B();
b.setC(new C());
Marshaller marshaller = jc.createMarshaller();
marshaller.marshal(b,System.out);
}
}
输出
2.1.2.v20101206-r8635
org.eclipse.persistence.jaxb.JAXBContext@100ab23
<?xml version="1.0" encoding="UTF-8"?>
<b xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="b"><c/></b>
更新
根据您的评论:
- B 不继承 A 的 XmlAccessorType 设置。
- 需要标记@XmlTransient 的不是抽象方法,而是用于在B 类上实现访问器的字段。
以下是 B 类的外观:
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class B extends A {
@XmlTransient
private C c;
@Override
public C getC() {
return c;
}
@Override
public void setC(C c) {
this.c = c;
}
}