I have been given an XSD which contains a xs:integer
field. I want the generated code to use an int
, so I can apply an existing interface to it. (the field is required and will never exceed the 32-bit range, it should have been an xs:int
).
Using XJB I can change the type in the generated code. But this gives me an error when creating a JAXBContext
.
<bindings
xmlns="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc">
<bindings schemaLocation="mySchema.xsd">
<bindings node="//xsd:element[@name='myField']">
<!-- either with jaxb -->
<property name="myField">
<baseType name="int">
<javaType name="int" />
</baseType>
</property>
<!-- or with xjc-->
<xjc:javaType name="int"/>
</bindings>
</bindings>
</bindings>
this generates the following code
public class MyClass {
@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(value = Adapter1.class)
@XmlSchemaType(name = "integer")
protected int myField;
// ...
}
While this works for code-generation, it fails for marshalling and throws the following exception when creating a context.
Adapter myPackage.Adapter1.class is not applicable to the field type int.
this problem is related to the following location:
at @javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter(type=javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter$DEFAULT.class, value=mySchemaPackage.Adapter1.class)
if I manually add a type-parameter to the annotation the problem is solved, but I cannot find a way to make JAXB do this for me.
@XmlJavaTypeAdapter(value = Adapter1.class, type = int.class)
Using the JAXB2-Basics -plugin I managed to override the generated annotation. I decided to use a named adapter instead of the dynamically generated Adapter1.class
, but the implementation of IntAdapter
is the same XmlAdapter<String, Integer>
as JAXB would generate.
<bindings
xmlns="http://java.sun.com/xml/ns/jaxb"
xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:annox="http://annox.dev.java.net">
<bindings schemaLocation="mySchema.xsd">
<bindings node="//xsd:element[@name='myField']">
<annox:annotate target="field">
@javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter(value=myCodePackage.IntAdapter.class, type=int.class)
</annox:annotate>
<xjc:javaType name="int" adapter="myCodePackage.IntAdapter"/>
</bindings>
</bindings>
</bindings>
and now the code is generated like
@XmlElement(required = true, type = String.class)
@XmlJavaTypeAdapter(value = IntAdapter.class, type = int.class)
@XmlSchemaType(name = "integer")
protected int myField;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.