/**
* @author liujh-r
* @date 2023/8/24 18:54
* @desc 校验主方法
* @param target 待校验目标
* @return 是否成功
**/
public static boolean valid(Object target) {
Field[] fields = target.getClass().getFields();
for (Field field : fields) {
Annotation[] annotations = field.getAnnotations();
if (annotations == null || annotations.length < 1) {
continue;
}
for (Annotation annotation : annotations) {
return validField(annotation, field, target);
}
}
return true;
}
private static boolean validField(Annotation validAction, Field field, Object target) {
try {
// 手机号校验的注解处理
if (validAction.annotationType().equals(PhoneCheck.class)) {
// 调用校验
return phoneCheck((PhoneCheck) validAction, field, target);
}
} catch (IllegalAccessException e) {
throw new RuntimeException("校验对象字段:" + target.getClass() + "." + field.getName() + "异常", e);
}
return true;
}
/**
* @author liujh-r
* @date 2023/8/24 17:57
* @desc 手机号码正则表达式校验基本逻辑
* @return 是否符合
**/
private static boolean phoneCheck(PhoneCheck phoneCheck, Field field, Object target) throws IllegalAccessException {
Object value = field.get(target);
if (value == null) return false;
String strValue = value.toString();
return strValue.matches(phoneCheck.pattern());
}