JAXB validation using annotations

Martin picture Martin · Mar 2, 2010 · Viewed 19.4k times · Source

If I have a simple class such as:-

@XmlRootElement
public class MyClass
{
   @XmlAttribute(required=true)
   private String myattribute
}

Is it possible to validate a corresponding xml document WITHOUT an xml schema i.e. using only the annotations?

Answer

skaffman picture skaffman · Mar 2, 2010

Good question. As far as I know, the required attribute is generated by XJC when it finds a non-optional schema type, and I think it's also used by the schema generator. At runtime, though, it's not used for anything, serving no other purpose than a documentary annotation.

One thing you could consider is the JAXB runtime's callback options. In this case, you could just define a afterUnmarshal() method on MyClass which programmatically validates the state of the object, throwing an exception if it doesn't like it. See the above link for other options, including registering separate validator classes.

Having said that, validation against a schema really is the best way. If you don't have one, you should considering writing one. The schemagen tool can generate a schema from your object model, which you can then modify to add whatever constraints you like. Hopefully, schemagen will generate mandatory schema elements from your required=true class fields.