自定義注解實現參數校驗


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、這里需要注意的是 參數校驗參數為空需拋出自定義異常


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM