我们经常会用到StringBuilder或StringBuffer类的append()方法,然而这里有个坑。
public static void main(String[] args) {
String ab = null;
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("测试");
if(null== ab) {
stringBuffer.append(ab);
}
System.out.println(ab);
System.out.println(stringBuffer.toString());
}
输出:
null
测试null
多了一个null字符串。
下面是撸源码时间←_←
java.lang.StringBuffer#append(java.lang.String)
public synchronized StringBuffer append(String str) {
super.append(str); //关键从这里进入
return this;
}
java.lang.AbstractStringBuilder#append(java.lang.String)
/**
* Appends the specified string to this character sequence.
* <p>
* The characters of the {@code String} argument are appended, in
* order, increasing the length of this sequence by the length of the
* argument. 这里: If {@code str} is {@code null}, then the four
* characters {@code "null"} are appended.
* 如果入参str是null,那么就会把“null”字符串给append进去。
* <p>
* Let <i>n</i> be the length of this character sequence just prior to
* execution of the {@code append} method. Then the character at
* index <i>k</i> in the new character sequence is equal to the character
* at index <i>k</i> in the old character sequence, if <i>k</i> is less
* than <i>n</i>; otherwise, it is equal to the character at index
* <i>k-n</i> in the argument {@code str}.
*
* @param str a string.
* @return a reference to this object.
*/
public AbstractStringBuilder append(String str) {
if (str == null) str = "null"; //就是这一步
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
上面的源码注释说的明明白白,jdk给多此一举的转换了[捂脸]!!!
所以如果你在组装返回给前端的数据时,使用到了append()方法,那么当你像下面的栗子一样使用append()方法时,请注意判空,负责会发生神马。。。。。。我神马都不知道,我神马都没说[捂脸]!!!:
append(coupon.getName());
改为:
String couponName = coupon.getName();
if(StringUtils.isNotBlank(couponName )){
append(couponName );
}