可修改做工具类
代码:
1. 待校验类:
public class User {
@NonNull(content = "姓名不能为空", minLen = 2, maxLen = 100)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2. 注解类
@Documented
@Target(value = ElementType.FIELD)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface NonNull {
String name() default "";
String content() default "";
int maxLen() default 50;
int minLen() default 1;
}
3. 校验
public void test() {
User user = new User();
user.setName("老王");
try {
valid(user);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private <T> void valid(T user) throws IllegalAccessException, InvocationTargetException {
Class<?> clazz = user.getClass();
Field[] declaredFields = clazz.getDeclaredFields();
Method[] methods = clazz.getMethods();
for (Field field : declaredFields) {
validParams(user, methods, field);
}
System.out.println("==========参数校验通过=========");
}
private <T> void validParams(T user, Method[] methods, Field field) throws IllegalAccessException, InvocationTargetException {
NonNull annotation = field.getAnnotation(NonNull.class);
String fieldName;
if (StringUtils.isNotBlank(annotation.name())) {
fieldName = annotation.name();
} else {
fieldName = field.getName();
}
for (Method method : methods) {
if (("get" + fieldName).toLowerCase().equals(method.getName().toLowerCase())) {
Object getMethodResult = method.invoke(user, null);
if (getMethodResult == null) {
System.out.println("==========非Null校验失败=========");
throw new IllegalArgumentException("[" + annotation.content() + "]为null");
}
if (getMethodResult instanceof String) {
if (StringUtils.isBlank(String.valueOf(getMethodResult))) {
System.out.println("==========非空校验失败=========");
throw new IllegalArgumentException("[" + annotation.content() + "]为空");
}
System.out.println(fieldName + "长度:" + String.valueOf(getMethodResult).length());
if (String.valueOf(getMethodResult).length() > annotation.maxLen()) {
System.out.println("==========长度超出指定范围=========");
throw new IllegalArgumentException("[" + fieldName + "]长度超出");
}
if (String.valueOf(getMethodResult).length() < annotation.minLen()) {
System.out.println("==========长度小于指定范围=========");
throw new IllegalArgumentException("[" + fieldName + "]长度不够");
}
}
}
}
}
结果参考:
name长度:2
==========参数校验通过=========
name长度:2
==========长度小于指定范围=========