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
你遇到的問題是小編創作靈感的來源!