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

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

实现思路:

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

文件介绍:

  • 1、CheckNull.java(自定义注解:校验非空字段)
  • 2、UserRegister.java(用户实体类)
  • 3、CommonUtils.java(公共工具类)
  • 4、Result.java(结果集返回包装类)
  • 5、CustBusinessException.java(自定义异常类)
  • 6、TestUtils.java(测试类)

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 csdn:seesun2012
 *
 */
@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 [email protected]
 *
 */
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 csdn:seesun2012
 *
 */
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 csdn:seesun2012
 *
 */
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;
	}

}


























注:以上内容仅提供参考和交流,请勿用于商业用途,如有侵权联系本人删除!


持续更新中…

如有对思路不清晰或有更好的解决思路,欢迎与本人交流,QQ群:273557553
你遇到的问题是小编创作灵感的来源!


你可能感兴趣的:(Java)