Java toString()方法经常报空指针

使用String.valueOf(obj)和obj.toString()返回相同的结果时,宁愿使用前者。

因为调用null对象的toString()会抛出空指针异常,如果我们能够使用valueOf()获得相同的值,那宁愿使用valueOf(),传递一个null给valueOf()将会返回“null”,尤其是在那些包装类,像Integer、Float、Double和BigDecimal。

BigDecimal bd = getPrice();

System.out.println(String.valueOf(bd)); //不会抛出空指针异常

System.out.println(bd.toString()); //抛出 "Exception in thread "main" java.lang.NullPointerException"

为了避免重复写判断空值,直接使用String.valueOf()即可。

附上该方法底层代码:

/**
Returns the string representation of the Object argument.
Params:obj – an Object.
Returns:if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
See Also:Object.toString()
**/
public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

你可能感兴趣的:(笔记,java,开发语言)