跟王老師學註解(六):註解應用案例

跟王老師學註解(六):註解應用案例

主講教師:王少華   QQ羣號:483773664

一、需求

利用註解,做一個Bean的數據校驗

要求:

用戶名是否能爲空,用戶名的長度不能超過指定長度,不能少於指定長度

二、參考代碼

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.PARAMETER })
public @interface MyValidate {
    // 是否可以爲空
    boolean nullable() default false;
 
    // 最大長度
    int maxLength() default 0;
 
    // 最小長度
    int minLength() default 0;
 
    // 參數或者字段描述,這樣能夠顯示友好的異常信息
    String description() default "";
}
public class User {
    @MyValidate(description="用戶名",minLength=6,maxLength=32,nullable=false)
    private String userName;
    public User(String userName) {
        super();
        this.userName = userName;
    }
}
public class ValidateService {
    // 解析的入口
    public static void valid(Object object) throws Exception {
        // 獲取object的類型
        Class<? extends Object> clazz = object.getClass();
        // 獲取該類型聲明的成員
        Field[] fields = clazz.getDeclaredFields();
        // 遍歷屬性
        for (Field field : fields) {
            // 對於private私有化的成員變量,通過setAccessible來修改器訪問權限
            field.setAccessible(true);
            validate(field, object);
            // 重新設置會私有權限
            field.setAccessible(false);
        }
    }
     
    public static void validate(Field field,Object object) throws Exception{
        String description;
        Object value;
  
        //獲取對象的成員的註解信息
        MyValidate dv=field.getAnnotation(MyValidate.class);
        value=field.get(object);
          
        if(dv==null)return;
          
        description=dv.description().equals("")?field.getName():dv.description();
          
        /*************註解解析工作開始******************/
        if(!dv.nullable()){
            if(value==null||value.toString()==""||"".equals(value.toString())){
                throw new Exception(description+"不能爲空");
            }
        }
          
        if(value.toString().length()>dv.maxLength()&&dv.maxLength()!=0){
            throw new Exception(description+"長度不能超過"+dv.maxLength());
        }
          
        if(value.toString().length()<dv.minLength()&&dv.minLength()!=0){
            throw new Exception(description+"長度不能小於"+dv.minLength());
        }
          
        /*************註解解析工作結束******************/
    }
}
public class Test {
    public static void main(String[] args) {
        User user = new User("張三");
        try {
            ValidateService.valid(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        user = new User("zhangsan");
        try {
            ValidateService.valid(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章