5.6.2 Replacing a Simple Type
Replacing a simple schema type such as string by some user defined
Java type is a little more complicated than what we have seen in the
previous section. We'll discuss the proceedings on the basis of this
type definition of a complex type meant to describe integer variables.
<xsd:complexType name="VariableType">
<xsd:sequence>
<xsd:element name="Value" type="xsd:int"/>
</xsd:sequence>
<xsd:attribute name="Impl" type="xsd:string"/>
</xsd:complexType>
The type we want to replace by customization is the one for the
attribute Impl
which is to be represented by the following
enum type.
package impl;
public enum ImplType {
UINT8( 1, false ), INT8( 1, true ),
// ...
UINT64(4,false), INT3644,true);
private final int bytes;
private final boolean signed;
ImplType( int b, boolean s ) {
bytes = b;
signed = s;
}
}
The utility class providing the conversions between a string
representation and the enum constants is easy.
package impl;
import java.util.*;
public class ImplConv {
public static ImplType parseStringToEnum( String value ){
return ImplType.valueOf( ImplType.class, value );
}
public static String printEnumToString( ImplType impl ){
return impl.toString();
}
}
Now we are prepared to set up the bindings file such as the one
shown below, in full. Notice the progressive restriction of the scope for the
binding specifications, first restricted to a specific schema
(i.e., signal.xsd
, then to the complex type definition for
VariableType
, and finally to its Impl
attribute node.
Also, the binding syntax requires that now, when we're substituting a
type of our own for a base type, the <jaxb:javaType>
element
must be enclosed in a <jaxb:baseType>
, and this, in turn, must
be wrapped by a <jaxb:property
element.
<?xml version="1.0" encoding="UTF-8"?>
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
jaxb:version="2.0">
<jaxb:bindings schemaLocation="signal.xsd" node="/xsd:schema">
<jaxb:schemaBindings>
<jaxb:package name="signal"/>
</jaxb:schemaBindings>
<jaxb:bindings node="//xsd:complexType[@name='VariableType']">
<jaxb:bindings node="./xsd:attribute[@name='Impl']">
<jaxb:property>
<jaxb:baseType>
<jaxb:javaType name="impl.ImplType"
parseMethod="impl.ImplConv.parseStringToEnum"
printMethod="impl.ImplConv.printEnumToString"/>
</jaxb:baseType>
</jaxb:property>
</jaxb:bindings>
</jaxb:bindings>
</jaxb:bindings>
</jaxb:bindings>
You can glean the reward of your pains from looking at the generated
code for the impl
field of VariableType
which lets
you now deal with this attribute via ImplType
enums, e.g.,:
ObjectFactory of = new ObjectFactory();
VariableType var = of.createVariableType();
var.setValue( 42 );
var.setImpl( ImplType.INT16 );