自定义注解实现参数校验

1、自定义注解

/**
 * @program:
 * @description: 自定义注解实现javabean属性校验
 * @author: Mr.zhourui
 * @create: 2020-07-03 17:10
 **/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD) //参数的位置
public @interface NotNull {
    //如果该属性有该注解 判断是否为空 如果为空返回异常信息
    String mesage() default "";
}

2、写一个反射类进行参数校验

/**
 * @program: zr
 * @description: 校验javabean是否为空
 * @author: Mr.zhourui
 * @create: 2020-07-03 17:18
 **/

public class CheakObjFiled {
  private static    Logger log= LoggerFactory.getLogger(CheakObjFiled.class);
    public static <T> void CheankObjectIsNot(T t) throws BizException, IllegalAccessException {
        if (t == null) {
            log.error("obj is null!!!");
            System.out.println(">>>>>>>obj is null!!!");
            throw new RuntimeException("obj is null!!!");
        }
        //获取class对象
        Class<?> aClass = t.getClass();
        //获取当前对象的所有属性 使用declared方法可以获取private属性
        Field[] fields = aClass.getDeclaredFields();
        //遍历对象属性
        for (Field field : fields) {
            //开启访问权限
            field.setAccessible(true);
            //field.get() 可以获取当前对象列的值
            Object o = field.get(t);
            Annotation annotation = field.getDeclaredAnnotation(NotNull.class);
            //如果没有设置当前注解不用校验
            if (annotation == null) {
                continue;
            }
            //获取注解接口对象
            NotNull notNull = (NotNull) annotation;
            //如果设置了当前注解但是没有值 ,抛出异常
            if(o==null){
                //如果没得值 设置了mesage 直接显示
                if(StringUtils.isNotBlank(notNull.mesage())){
                    log.error(">>>>>>>obj is null!!!");
                    System.out.println(">>>>>>>obj is null!!!");
                    throw new BizException(ErrorCode.PARAMS_ERROR.getCode(), notNull.mesage()+"is null");
                }else {
                    log.error(">>>>>>>obj is null!!!");
                    System.out.println(">>>>>>>obj is null!!!");
                    throw new BizException(ErrorCode.PARAMS_ERROR.getCode(), notNull.mesage()+"is null");
                }
            }

        }
    }
}

3、使用

 4、这里需要注意的是 参数校验参数为空需抛出自定义异常

原文地址:https://www.cnblogs.com/zrboke/p/13792401.html