java判斷l(xiāng)ist不為空的實(shí)現(xiàn),和限制條數(shù)不要在一起寫
場(chǎng)景
很多情況下,查單條記錄也用通用查詢接口,但是輸入的條件卻能確定唯一性。如果我們要確定list中只有一條記錄,如下寫法:
// 記錄不為空 && 只有一條 才繼續(xù) if(!CollectionUtils.isEmpty(list) && 1!=list.size()){ return "記錄條數(shù)不是1"; } Object object = list.get(0);
上面代碼對(duì)么,貌似正確啊。后來報(bào)錯(cuò)了,被打臉了。
其實(shí)相當(dāng)于 >0 && !=1 恰好漏掉了 =0 這種情況,
因此get(0)完美報(bào)錯(cuò)。
解決方案
像這種條件不要怕麻煩,多寫幾個(gè)if更清晰。
補(bǔ)充:判斷一個(gè)java對(duì)象中的屬性值是否為空(批量判斷)
有時(shí)候數(shù)據(jù)庫(kù)中的某些字段值要求不為空,所以代碼中要判斷這些字段對(duì)應(yīng)的屬性值是否為空,當(dāng)對(duì)象屬性過多時(shí),一個(gè)一個(gè)屬性去判斷,會(huì)顯得代碼冗余,所以,可以借助工具類
import org.apache.commons.lang.StringUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.FatalBeanException; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class IsNull { //整個(gè)類都校驗(yàn) public static List<String> validateProperty(Object validateObj) { return validateProperty(validateObj,(String[])null); } //類中的某些字段不校驗(yàn) public static List<String> validateProperty(Object validateObj,String... ignoreProperties) { PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(validateObj.getClass()); List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null); List<String> errList = new ArrayList<>(); for (PropertyDescriptor targetPd : targetPds) { Method readMethod = targetPd.getReadMethod(); if (readMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) { try { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(validateObj); if (value instanceof String) { if (StringUtils.isEmpty((String) value)) { errList.add(validateObj.getClass().getSimpleName()+ "中的" + targetPd.getName() + "不能為空"); continue; } } if (value instanceof Float || value instanceof Integer) { if (StringUtils.isEmpty(value.toString())) { errList.add(validateObj.getClass().getSimpleName()+ "中的" + targetPd.getName() + "不能為空"); continue; } } if (value == null) { errList.add(validateObj.getClass().getSimpleName() + "中的" + targetPd.getName() + "不能為空"); } } catch (Throwable ex) { throw new FatalBeanException( "Could not copy property '" + targetPd.getName() + "' from source to target", ex); } } } return errList; } }
之后對(duì)拿到的數(shù)據(jù)進(jìn)行業(yè)務(wù)判斷
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
springboot整合swagger3報(bào)Unable to infer base&nbs
這篇文章主要介紹了springboot整合swagger3報(bào)Unable to infer base url錯(cuò)誤問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05spring的jdbctemplate的crud的基類dao
本文主要介紹了使用spring的jdbctemplate進(jìn)行增刪改查的基類Dao的簡(jiǎn)單寫法,需要的朋友可以參考下2014-02-02- Guava是Google發(fā)布的一個(gè)開源庫(kù),主要提供了一些在Java開發(fā)中非常有用的工具類和API,不管是工作還是學(xué)習(xí)都是非常值得我們?nèi)ナ煜さ?,一起來看看?/div> 2023-03-03
最新評(píng)論