![](/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.