本文目标:开发人员,在了解Hutool工具进行对象判空方法的条件下,进行对象判空,达到更准确的进行判空操作,简化代码的程度。
1 工具应用场景
Hutool工具对jdk进行了封装,补充考虑了异常场景,提供的方法质量更高,更简洁。
本文使用其对象判空相关方法。
java中常见需要判空的数据类型有字符串、集合、数组、对象,下文依次介绍。
2 使用效果
使用Hutool工具提供的方法,基本可以做到一次方法调用,实现直接使用jdk多次操作的效果,代码看上去更简洁。
2.1 字符串判空
使用jdk方式判空。
String a = "";
if (null==a || a.length()==0) {
System.out.println("a is empty!");
}
使用Hutool工具提供的方法判空。
String a = "";
if (StrUtil.isEmpty(a)) {
System.out.println("a is empty!");
}
程序结果打印:
2.2 字符串不为空但内容为空字符判断
使用jdk方式判空。
String b = " ";
if (null!=b && b.length()!=0) {
int count = 0; //比较次数
//遍历字符串,检查是否存在非空白字符
for (int i=0; i<b.length(); i++,count++) {
if (!Character.isWhitespace(b.charAt(i))) {
System.out.println("b is not blank!");
}
}
//若比较次数与字符串长度相等,表示内容均为空白字符
if (count == b.length()) {
System.out.println("b is blank!");
}
} else {
System.out.println("b is blank!");
}
使用Hutool工具提供的方法判空。
String b = " ";
if (StrUtil.isBlank(b)) {
System.out.println("b is blank!");
}
程序结果打印:
Hutool提供的字符串内容空白判断方法,除了jdk中isWhitespace判断空白符外,还考虑其他多中无意义的字符,场景更全面。
感兴趣的可以查看源码。
2.3 集合判空
使用jdk方式判空。
List c = new ArrayList<>();
if (null == c || c.isEmpty()) {
System.out.println("c is empty!");
}
使用Hutool工具提供的方法判空。
List c = new ArrayList<>();
if (CollUtil.isEmpty(c)) {
System.out.println("c is empty!");
}
程序结果打印:
2.4 数组判空
使用jdk方式判空。
String[] d = {};
if (null==d || d.length==0) {
System.out.println("d is empty!");
}
使用Hutool工具提供的方法判空。
String[] d = {};
if (ArrayUtil.isEmpty(d)) {
System.out.println("d is empty!");
}
程序结果打印:
2.5 对象判空
使用jdk方式判空。
Object f = new Object();
if (null != f) {
//通过反射获取对象的所有属性
Field[] var2 = ReflectUtil.getFields(f.getClass());
int var3 = var2.length;
int count = 0; //比较次数
//遍历每个属性
for(int var4 = 0; var4 < var3; ++var4, ++count) {
Field field = var2[var4];
//若存在值不为空,则表示对象内容不为空
if (!ModifierUtil.isStatic(field) && null != ReflectUtil.getFieldValue(f, field)) {
System.out.println("f is not empty!");
}
}
//若比较次数与属性个数相等,表示对象内容为空
if (count == var3) {
System.out.println("f is empty!");
}
} else {
System.out.println("f is empty!");
}
使用Hutool工具提供的方法判空。
Object f = new Object();
if (BeanUtil.isEmpty(f)) {
System.out.println("f is empty!");
}
程序结果打印:
Hutool提供的对象判空方法,也是基于反射实现,对于性能比较敏感的系统,谨慎使用。
3 使用方法
代码参见“2 使用效果”章节,只需要引入Hutool工具的jar包。
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.20</version>
</dependency>
4 总结/练习
本文介绍了Hutool工具提供的对象判空方法,可以在自己的项目中尝试使用,达到提高代码质量,简化代码的效果。