问题描述
@Target({TYPE,ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = PhoneOrEmailPresentedValidator.class)
@Documented
public @interface PhoneOrEmailPresented {
String message() default "Either phone or email should be presented";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
和验证器:
public class PhoneOrEmailPresentedValidator implements ConstraintValidator<PhoneOrEmailPresented,RequestDto> {
@Override
public boolean isValid(RequestDto value,ConstraintValidatorContext context) {
String email = value.getEmail();
String phone = value.getPhone();
return (email != null && !email.isEmpty()) ||
(phone != null && !phone.isEmpty());
}
@Override
public void initialize(PhoneOrEmailPresented constraintAnnotation) {
// nop
}
}
我想在具有与isValid()
方法中所示的相同字段的另一个DTO上使用此批注。
解决方法
由于没有找到验证API的方法,因此可以通过反射来解决问题(借助于类org.apache.commons.lang3.reflect.FieldUtils
,Java也可以做到这一点)
String email,phone;
try {
Field emailField = FieldUtils.getField(value.getClass(),"email",true);
Field phoneField = FieldUtils.getField(value.getClass(),"phone",true);
email = (String) emailField.get(value);
phone = (String) phoneField.get(value);
} catch (IllegalAccessException e) {
e.printStackTrace();
return false;
}