![](/img/trans.png)
[英]Using java.util.Locale in JAXB generated classes using XmlAdapter
[英]How to use XmlAdapter to map XML complex types to Java objects in schema-generated classes?
使用此(演示)模式,我使用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实现。 如非官方JAXB指南中的3.2.2节所建议。 使用@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; lineNumber:8; columnNumber:22; 未定义的简单类型“ { http://www.example.com } otherType”。
经过一番探索 ,我发现在模式生成的类中为复杂类型使用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年以来,有人可能找到了解决此问题的方法...
您可以使用jaxb2 annotate
maven插件将注释添加到生成的JAXB
类中。
<plugin>
<!-- this plugin is used to add annotation for the models -->
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-basics-annotate</artifactId>
<version>1.0.2</version>
</plugin>
在.xjb
绑定中,
<jxb:bindings schemaLocation="sample.xsd">
<jxb:bindings node="//xs:complexType[@name='otherType']">
<annox:annotate target="field">
<annox:annotate annox:class="@javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter"
value="com.example.OtherTypeAdapter.class" />
</annox:annotate>
</jxb:bindings>
</jxb:bindings>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.