java实体类属性非空判断工具类
生活随笔
收集整理的這篇文章主要介紹了
java实体类属性非空判断工具类
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;public class CheckParametersUtil {Map<String, Object> map = new HashMap<>();/*** 添加需要校驗的參數(shù)* @param object 實參* @param parameterName 參數(shù)名稱*/public CheckParametersUtil put(String parameterName,Object object) {map.put(parameterName, object);return this;}/*** 獲取CheckParametersUtil實例*/public static CheckParametersUtil getInstance(){return new CheckParametersUtil();}/*** 校驗*/public void checkParameter() throws Exception {for(Entry<String, Object> entry : map.entrySet()) {if(isEmptyTrim(entry.getValue())){throw new Exception("參數(shù)【" + entry.getKey() + "】為空" );}}}public String toString(Object object) {return object == null ? "" : object.toString();}public boolean isEmpty(Collection collection) {return collection == null || collection.isEmpty();}public boolean isEmpty(Map map) {return map == null || map.isEmpty();}public boolean isEmpty(String string) {return toString(string).isEmpty();}public boolean isEmptyTrim(String string) {return toString(string).trim().isEmpty();}public boolean isEmpty(Object object) {return toString(object).isEmpty();}public boolean isEmptyTrim(Object object) {return toString(object).trim().isEmpty();}public <T> boolean isEmpty(T[] array) {return array == null || array.length == 0;}
}
校驗
public R addFileInfo(@RequestBody User user){try {CheckParametersUtil.getInstance().put(user.getId(),"id") //左邊的是參數(shù)值,右邊是參數(shù)名稱.put(user.getName(),"name").put(user.getSex(),"sex").checkParameter();return R.ok();}catch (Exception e){return R.error(e.getMessage());}}結果
{"msg": "參數(shù)【name】為空","code": 500,"success": false }總結
以上是生活随笔為你收集整理的java实体类属性非空判断工具类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PWN-PRACTICE-CTFSHOW
- 下一篇: java8 stream流操作集合交集,