Null的Java注释,但既不是Empty也不是Blank [英] Java annotation for Null but neither Empty nor Blank
问题描述
是否有任何可以像下面的示例一样验证的java注释?
Is there are any java annotation(s) that can validate like the example below ?
String test;
test = null; //valid
test = ""; //invalid
test = " "; //invalid
test = "Some values"; //valid
提前致谢
推荐答案
javax.validation或Hibernate Validator中都没有这样的注释。有一个请求将一个添加到Hibernate Validator 但它已关闭,因为不会修复由于相对容易编写自己的可能性。建议的解决方案是使用你自己定义的注释类型:
There isn't such an annotation in either javax.validation or Hibernate Validator. There was a request to add one to Hibernate Validator but it was closed as "won't fix" due to the possibility of writing your own relatively easily. The suggest solution was to either use your own annotation type defined like this:
@ConstraintComposition(OR)
@Null
@NotBlank
@ReportAsSingleViolation
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Constraint(validatedBy = { })
public @interface NullOrNotBlank {
String message() default "{org.hibernate.validator.constraints.NullOrNotBlank.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
或使用 @Pattern
带有正则表达式的注释,需要存在非空白字符(作为模式注释接受空值并且与模式不匹配。
or to use the @Pattern
annotation with a regular expression that requires a non-whitespace character to be present (as the Pattern annotation accepts nulls and does not match them against the pattern).
这篇关于Null的Java注释,但既不是Empty也不是Blank的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!