java判斷list不為空的實現,和限制條數不要在一起寫
很多情況下,查單條記錄也用通用查詢接口,但是輸入的條件卻能確定唯一性。如果我們要確定list中只有一條記錄,如下寫法:
// 記錄不為空 && 只有一條 才繼續if(!CollectionUtils.isEmpty(list) && 1!=list.size()){ return '記錄條數不是1';}Object object = list.get(0);
上面代碼對么,貌似正確啊。后來報錯了,被打臉了。
其實相當于 >0 && !=1 恰好漏掉了 =0 這種情況,
因此get(0)完美報錯。
解決方案像這種條件不要怕麻煩,多寫幾個if更清晰。
補充:判斷一個java對象中的屬性值是否為空(批量判斷)
有時候數據庫中的某些字段值要求不為空,所以代碼中要判斷這些字段對應的屬性值是否為空,當對象屬性過多時,一個一個屬性去判斷,會顯得代碼冗余,所以,可以借助工具類
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 { //整個類都校驗 public static List<String> validateProperty(Object validateObj) { return validateProperty(validateObj,(String[])null); } //類中的某些字段不校驗 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; }}
之后對拿到的數據進行業務判斷
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。