import cn.hutool.core.annotation.AnnotationUtil;
/**
* 用的是hutool的工具类,需要先引入依赖
*/
public static <T> void notNullVerify (List<T> list) {
T t = list.get(0);
Class<?> aClass = list.get(0).getClass();
// 所有字段
Field[] fields = aClass.getDeclaredFields();
try {
for (Field field : fields) {
// 只判断该字段拥有非空注解
if (AnnotationUtil.hasAnnotation(field, NotBlank.class)){
// 私有可访问
field.setAccessible(true);
//获取属性的名字
String name = field.getName();
//将属性名字的首字母大写
name = name.replaceFirst(name.substring(0, 1), name.substring(0, 1).toUpperCase());
//整合出 get() 属性这个方法
Method m = aClass.getMethod("get"+name);
// 字段实例
Object property = m.invoke(t);
if (property == null || property.toString().trim().isEmpty()){
// 获取指定注解内属性值
Object annotationValue = AnnotationUtil.getAnnotationValue(field, NotBlank.class,"message");
throw new BusinessException(annotationValue.toString());
}
}
}
} catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
e.printStackTrace();
throw new BusinessException("校验失败");
}
}
java 获取泛型对象属性值 获取注解内属性值
最新推荐文章于 2024-07-21 22:27:18 发布