java JAXB required=true 似乎不需要
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2669632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JAXB required=true doesn't seem to require
提问by Marcus Leon
We have this JAXB annotation:
我们有这个 JAXB 注释:
@XmlElement(name = "Strategy", required = true)
protected List<Strategy> strategy;
If there are no Strategyelements present, no exception is thrown.. why is this? Shouldn't we get an exception?
如果没有Strategy元素存在,则不会抛出异常..这是为什么?我们不应该得到一个例外吗?
回答by skaffman
The JAXB reference implementation doesn't use this attribute for validation, it's purely there for documentation purposes.
JAXB 参考实现不使用此属性进行验证,它纯粹用于文档目的。
If you need to validate the documents, you need to define an XML Schema, and inject it into the Marshalleror Unmarshaller, using SchemaFactory.
如果您需要验证文档,您需要定义一个 XML 模式,并将其注入到Marshalleror 中Unmarshaller,使用SchemaFactory.
回答by Ryan Ransford
Additionally, you could use the beforeMarshaland afterUnmarshalmethods to validate inputs as spec'd in Marshallerand Unmarshaller.
此外,您可以使用beforeMarshal和afterUnmarshal方法来验证Marshaller和Unmarshaller 中规范的输入。
The scheme under which these methods are accessed will also allow you to add an arbitrary throwsclause to the method declaration. This means that when implementing these methods, you can safely use javax.xml.bind.MarshalExceptionand javax.xml.bind.UnmarshalException(or whatever sort of Exceptionyou want)to signal validation errors.
访问这些方法的方案还允许您throws在方法声明中添加任意子句。这意味着在实现这些方法时,您可以安全地使用javax.xml.bind.MarshalException和javax.xml.bind.UnmarshalException(或Exception您想要的任何类型)来表示验证错误。

