Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB required=true doesn't seem to require

Tags:

java

xml

jaxb

We have this JAXB annotation:

 @XmlElement(name = "Strategy", required = true)
 protected List<Strategy> strategy;

If there are no Strategy elements present, no exception is thrown.. why is this? Shouldn't we get an exception?

like image 691
Marcus Leon Avatar asked Apr 19 '10 17:04

Marcus Leon


2 Answers

The JAXB reference implementation doesn't use this attribute for validation, it's purely there for documentation purposes.

If you need to validate the documents, you need to define an XML Schema, and inject it into the Marshaller or Unmarshaller, using SchemaFactory.

like image 61
skaffman Avatar answered Nov 19 '22 17:11

skaffman


Additionally, you could use the beforeMarshal and afterUnmarshal methods to validate inputs as spec'd in Marshaller and Unmarshaller.

The scheme under which these methods are accessed will also allow you to add an arbitrary throws clause to the method declaration. This means that when implementing these methods, you can safely use javax.xml.bind.MarshalException and javax.xml.bind.UnmarshalException (or whatever sort of Exception you want) to signal validation errors.

like image 36
Ryan Ransford Avatar answered Nov 19 '22 15:11

Ryan Ransford