是否有任何Java注释可以验证,例如下面的示例?

String test;
test = null; //valid
test = ""; //invalid
test = " "; //invalid
test = "Some values"; //valid

最佳答案

您需要创建一个自定义注释:@NullOrNotBlank
首先创建自定义注释:NullOrNotBlank.java

@Target( {ElementType.FIELD})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = NullOrNotBlankValidator.class)
public @interface NullOrNotBlank {
    String message() default "{javax.validation.constraints.Pattern.message}";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default {};
}

然后是实际的 validator :NullOrNotBlankValidator.java
public class NullOrNotBlankValidator implements ConstraintValidator<NullOrNotBlank, String> {

    public void initialize(NullOrNotBlank parameters) {
        // Nothing to do here
    }

    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        return value == null || value.trim().length() > 0;
    }
}

关于java - Java注释为空,但不为空也不为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31132477/

10-10 07:54