【发布时间】:2017-01-01 15:08:09
【问题描述】:
使用这个(演示)模式,我正在使用 JAXB 生成 Java 对象:
<xsd:complexType name="someType">
<xsd:sequence>
<xsd:element name="myOtherType" type="otherType" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="otherType">
<!-- ... -->
</xsd:complexType>
生成此类:
@XmlType
public class SomeType {
@XmlElement(name = "myOtherType")
OtherType myOtherType;
}
但我想在我的 JAXB 生成的对象中使用接口而不是实现。
所以我写了这个界面:
public interface OtherTypeInterface {
// ....
}
我让生成的 OtherType 类在绑定文件的帮助下实现它:
<jxb:bindings node="//xs:complexType[@name='otherType']">
<inheritance:implements>com.example.OtherTypeInterface</inheritance:implements>
</jxb:bindings>
到目前为止,一切都很好:
public class OtherType implements OtherTypeInterface {
// ...
}
但是我也需要 SomeType 对象来使用这个接口,而不是 OtherType 实现。正如在3.2.2 节中建议的in the unofficial JAXB guide。使用@XmlJavaTypeAdapter,我想使用自制的XML适配器将OtherType映射到它的接口,反之亦然:
public class HcpartyTypeAdapter extends XmlAdapter<OtherType, OtherTypeInterface> {
@Override
public OtherTypeInterface unmarshal(OtherType v) throws Exception {
return v;
}
@Override
public OtherType marshal(OtherTypeInterface v) throws Exception {
return (OtherType) v;
}
}
但看起来在我的绑定文件中使用以下配置映射 XML 复杂类型是一个很大的禁忌:
<jxb:globalBindings>
<xjc:javaType name="com.example.OtherTypeInterface" xmlType="ex:otherType" adapter="com.example.OtherTypeAdapter"/>
</jxb:globalBindings>
生成失败并出现此错误:
com.sun.istack.SAXParseException2; systemId:文件:/.../bindings.xjb; 行号:8;列号:22;未定义的简单类型 “{http://www.example.com}其他类型”。
使用a bit of googling,我发现显然不可能在模式生成的类中对复杂类型使用XML 适配器。但是,如果我手动编辑文件以使用我的适配器,它会完美运行:
public class SomeType {
@XmlElement(name = "myOtherType")
@XmlJavaTypeAdapter(OtherTypeAdapter.class)
@XmlSchemaType(name = "otherType")
OtherTypeInterface myOtherType;
}
我可以完美地编组和解组它;但在我看来,编辑生成的类违背了自动处理的全部目的。我正在处理定义许多类型的多个模式。
所以我的问题是:有没有人知道一种解决方法,可以使用 XML 适配器将 XML 复杂类型映射到模式生成的类中的 Java 对象,而无需手动编辑代码?
这里的潜在答案:https://stackoverflow.com/a/1889584/946800。我希望自 2009 年以来,有人可能已经找到了解决此问题的方法...
【问题讨论】: