• Java自定义注解源码+原理解释(使用Java自定义注解校验bean传入参数合法性)


    Java自定义注解源码+原理解释(使用Java自定义注解校验bean传入参数合法性)

    前言:由于前段时间忙于写接口,在接口中需要做很多的参数校验,本着简洁、高效的原则,便写了这个小工具供自己使用(内容为缩减版,具体业务可自行扩展)

    思路:使用Java反射机制,读取实体类属性头部注解,通过get方法获取参数值进行校验,如果为空则进行异常抛出

    CheckNull.java 类

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

    Userregister.java 类

    package com.seesun2012.common.entity;
    
    import java.io.Serializable;
    
    import com.seesun2012.common.annotation.CheckNull;
    
    /**
     * 用户注册实体类
     *
     * @author seesun2012@163.com
     *
     */
    public class Userregister implements Serializable{
    
    	private static final long serialVersionUID = 1L;
    	
    	//自定义注解
    	@CheckNull(message="用户名不能为空")
    	private String userAccount;
    	//自定义注解
    	@CheckNull(message="密码不能为空")
    	private String passWord;
    
    	public String getUserAccount() { return userAccount; }
    	public void setUserAccount(String userAccount) { this.userAccount = userAccount; }
    	public String getPassWord() { return passWord; }
    	public void setPassWord(String passWord) { this.passWord = passWord; }
    
    	@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();
        }
    }
    
    

    CommonUtils.java 类

    package com.seesun2012.common.utils;
    
    import java.beans.BeanInfo;
    import java.beans.Introspector;
    import java.beans.PropertyDescriptor;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.util.List;
    
    import com.seesun2012.common.annotation.CheckNull;
    import com.seesun2012.common.exception.CustBusinessException;
    
    /**
     * 公共工具类
     *
     * @author seesun2012@163.com
     *
     */
    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.getDeclaredAnnotation(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(null!=msg){
                throw new CustBusinessException(msg);
            }
    	}
    	
    }
    

    Result.java 类

    package com.seesun2012.common.entity;
    
    import java.io.Serializable;
    import java.util.HashMap;
    
    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);
    	}
    
    }
    
    
    

    CustBusinessException.java 类

    package com.seesun2012.common.exception;
    
    /**
     * 自定义异常类
     *
     * @author seesun2012@163.com
     *
     */
    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);
    	}
    
    }
    
    

    TestUtils.java 类

    package com.seesun2012.test.utils;
    
    import com.seesun2012.common.entity.Result;
    import com.seesun2012.common.entity.Userregister;
    import com.seesun2012.common.utils.CommonUtils;
    
    public class TestUtils{
    
    	public static void main(String[] args) {
    		Userregister sss = new Userregister();
    		sss.setUserAccount("asdflkjasokdfj");
    		System.out.println(insertUser(sss));
    	}
    
    	public static Result insertUser(Userregister param){
    		Result result = new Result(1, "新增失败");
    		try {
    			CommonUtils.doValidator(param);
    			result = Result.build(0, "新增成功");
            } catch (Exception e) {
            	result =  Result.build(1, e.getMessage());
            }
    		return result;
    	}
    
    }
    

    结语:该用户暂未添加

  • 相关阅读:
    3.10 Go Map哈希表
    3.9 Go Slice切片
    3.8 Go Array数组
    3.7 Go指针
    3.6 Go String型
    3.5 Go布尔型
    3.4 Go字符型
    3.3 Go浮点型
    3.2 Go整数类型
    3.1Go变量
  • 原文地址:https://www.cnblogs.com/seesun2012/p/9214632.html
Copyright © 2020-2023  润新知