java自定义注解代码练习

/**
 * 自定义注解:校验非空字段
 *
 */
@Documented
@Inherited
// 接口、类、枚举、注解
@Target(ElementType.FIELD)
//只是在运行时通过反射机制来获取注解,然后自己写相应逻辑(所谓注解解析器)
@Retention(RetentionPolicy.RUNTIME)
public @interface CheckNull {
    String message() default "默认值为0";
}

  

/**
 * 用户实体类
 *
 */
public class UserRegister implements Serializable {

    private static final long serialVersionUID = 1L;

    //自定义注解
    @CheckNull(message="用户名不能为空")
    private String userAccount;
    //自定义注解
    @CheckNull(message="密码不能为空")
    private String passWord;

    private UserRegister(Builder builder){
        this.userAccount = builder.userAccount;
        this.passWord = builder.passWord;
    }
    public static class Builder{
        private String userAccount;
        private String passWord;

        public Builder userAccount(String userAccount){
            this.userAccount = userAccount;
            return this;
        }

        public  Builder passWord(String passWord){
            this.passWord = passWord;
            return this;
        }

        public UserRegister build(){
            return new UserRegister(this);
        }
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", userAccount=").append(userAccount);
        sb.append(", passWord=").append(passWord);
        sb.append(", serialVersionUID=").append(serialVersionUID);
        sb.append("]");
        return sb.toString();
    }
}

  

/**
 * 自定义异常类
 *
 */
public class CustBusinessException extends RuntimeException{

    private static final long serialVersionUID = 1L;

    public CustBusinessException(){

    }

    public CustBusinessException(String str){
        super(str);
    }

    public CustBusinessException(Throwable throwable){
        super(throwable);
    }

    public CustBusinessException(String str, Throwable throwable){
        super(str, throwable);
    }

}

  

/**
 * 公共工具类
 *
 */
public class CommonUtils{

    /**
     * 通过反射来获取javaBean上的注解信息,判断属性值信息,然后通过注解元数据来返回
     */
    public static <T> boolean doValidator(T clas){
        Class<?> clazz = clas.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            CheckNull checkNull = field.getAnnotation(CheckNull.class);
            if (null!=checkNull) {
                Object value = getValue(clas, field.getName());
                if (!notNull(value)) {
                    throwExcpetion(checkNull.message());
                }
            }
        }
        return true;
    }

    /**
     * 获取当前fieldName对应的值
     *
     * @param clas		对应的bean对象
     * @param fieldName	bean中对应的属性名称
     * @return
     */
    public static <T> Object getValue(T clas,String fieldName){
        Object value = null;
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(clas.getClass());
            PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : props) {
                if (fieldName.equals(property.getName())) {
                    Method method = property.getReadMethod();
                    value = method.invoke(clas, new Object[]{});
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 非空校验
     *
     * @param value
     * @return
     */
    public static boolean notNull(Object value){
        if(null==value){
            return false;
        }
        if(value instanceof String && isEmpty((String)value)){
            return false;
        }
        if(value instanceof List && isEmpty((List<?>)value)){
            return false;
        }
        return null!=value;
    }

    public static boolean isEmpty(String str){
        return null==str || str.isEmpty();
    }
    public static boolean isEmpty(List<?> list){
        return null==list || list.isEmpty();
    }

    private static void throwExcpetion(String msg) {
        if(isEmpty(msg)){
            throw new CustBusinessException(msg);
        }
    }

}

  

public class TestUtils{

    public static void main(String[] args) {
        UserRegister userRegister = new UserRegister.Builder().userAccount("小小高").passWord("123456").build();
        System.out.println(insertUser(userRegister));
        System.out.println(userRegister.toString());
    }

    public static Result insertUser(UserRegister param){
//        Result result = new Result(1, "新增失败");
        Result result;
        try {
            CommonUtils.doValidator(param);
            result = Result.build(0, "新增成功");
        } catch (Exception e) {
            result =  Result.build(1, e.getMessage());
        }
        return result;
    }

}

  

/**
 * 结果集返回包装类
 */
public class Result extends HashMap<String, Object> implements Serializable {

    private static final long serialVersionUID = 1L;

    public static final Result SUCCEED = new Result(0, "操作成功");

    public Result(int status, String massage) {
        super();
        this.put("status", status).put("message", massage);
    }

    public Result put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public static Result build(int i, String message) {
        return new Result(i, message);
    }

}

  

posted @ 2019-04-10 14:16  A小小高  阅读(529)  评论(0编辑  收藏  举报