背景是接口导入时,部分字段因为手动录入可能误输空格,所以需去掉前后空格,这些属性为非必填,所以未校验非空,引发空指针异常。
代码类似这样,未判断是否为空,直接trim,导致空指针异常
@Test
public void test(){
String a = " a ";
String b = " ";
String c = " ";
String d = null;
System.out.println("a: " + StringUtils.isEmpty(a));
System.out.println("b: " + StringUtils.isEmpty(b));
System.out.println("c: " + StringUtils.isEmpty(c));
System.out.println("d: " + StringUtils.isEmpty(d));
System.out.println("a.trim: " + StringUtils.isEmpty(a.trim()));
System.out.println("b.trim: " + StringUtils.isEmpty(b.trim()));
System.out.println("c.trim: " + StringUtils.isEmpty(c.trim()));
System.out.println("d.trim: " + StringUtils.isEmpty(d.trim()));
}
trim源码如下
public static String trim(byte[] value) {
int len = value.length;
int st = 0;
while ((st < len) && ((value[st] & 0xff) <= ' ')) {
st++;
}
while ((st < len) && ((value[len - 1] & 0xff) <= ' ')) {
len--;
}
return ((st > 0) || (len < value.length)) ?
newString(value, st, len - st) : null;
}
合理的使用应该加上判断
if(!StringUtils.isEmpty(d)){
System.out.println("d.trim: " + StringUtils.isEmpty(d.trim()));
}