String.valueOf()方法当传入的参数为一个引用且该引用引用的是null时,方法返回字符串"null",此时若用StringUtils.isBlank()这类方法判断时将返回true,因为此时调用的valueOf(Object obj)方法,该方法的源码如下(jdk1.8.0_131中String的部分源码):
/**
* Returns the string representation of the {@code Object} argument.
*
* @param obj an {@code Object}.
* @return if the argument is {@code null}, then a string equal to
* {@code "null"}; otherwise, the value of
* {@code obj.toString()} is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
调用String.valueOf()时若实参直接写为null,方法会报NPE,通过IDE可以看出,valueOf(null)调用的String类的方法如下(jdk1.8.0_131中String的部分源码):
/**
* Returns the string representation of the {@code char} array
* argument. The contents of the character array are copied; subsequent
* modification of the character array does not affect the returned
* string.
*
* @param data the character array.
* @return a {@code String} that contains the characters of the
* character array.
*/
public static String valueOf(char data[]) {
return new String(data);
}
而上述源码的中new String(data)又会调用如下方法(jdk1.8.0_131中String的部分源码):/**
* Allocates a new {@code String} so that it represents the sequence of
* characters currently contained in the character array argument. The
* contents of the character array are copied; subsequent modification of
* the character array does not affect the newly created string.
*
* @param value
* The initial value of the string
*/
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length); //value[]为null时,报NPE
}
鉴于valueOf()可能会返回"null"字符串,使用时要特别注意,不能再用StringUtils.isEmpty()或isBlank()来简单地判断valueOf()返回值是否为空了。