java判断list不为空的实现,和限制条数不要在一起写
时间:2021-04-27 09:09:29|栏目:JAVA代码|点击: 次
场景
很多情况下,查单条记录也用通用查询接口,但是输入的条件却能确定唯一性。如果我们要确定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;
}
}
之后对拿到的数据进行业务判断
栏 目:JAVA代码
下一篇:使用fastjson中的JSONPath处理json数据的方法
本文标题:java判断list不为空的实现,和限制条数不要在一起写
本文地址:http://www.codeinn.net/misctech/109889.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




