Does JAXB support xsd:restriction?

Narendra Pathai picture Narendra Pathai · Dec 8, 2012 · Viewed 17.2k times · Source
<xs:element name="age">
  <xs:simpleType>
    <xs:restriction base="xs:integer">
      <xs:minInclusive value="0"/>
      <xs:maxInclusive value="120"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

So I want it to get converted to Java code like this:

public void setAge(int age){
    if(age < 0 || age > 120){
         //throw some exception
    }
     //setting the age as it is a valid value
}

Is it possible in JAXB?

Had seen some WebService Client stub generator doing this maybe axis2 webservice but not sure.

Answer

bdoughan picture bdoughan · Dec 12, 2012

The JAXB (JSR-222) specification does not cover generating fail fast logic into the domain model. A common practice now is to express validation rules in the form of annotations (or XML) and run validation on them. Bean Validation (JSR-303) standardizes this and is available in any Java EE 6 implementation.

XJC Extensions

I have not tried the following extension myself but it appears as though it will generate Bean Validation (JSR-303) annotations onto the domain model representation validation rules from the XML schema. As XJC is very extensible there may be other plug-ins available as well.