考虑下面一个:
Object nothingToHold = null;
System.out.println(nothingToHold); // Safely prints 'null'
在这里,Sysout必须期待String.
因此必须在实例上调用toString().
那么为什么null.toString()工作得很棒? Sysout会照顾这个吗?
编辑:其实我用StringBuilder的append()看到了这个奇怪的东西.所以尝试了Sysout.两者的行为方式相同.那个方法也在照顾吗?
解决方法:
PrintWriter的println(Object)(当你编写System.out.println(nothingToHold)时调用的方法)调用String.valueOf(x),如Javadoc中所述:
/**
* Prints an Object and then terminates the line. This method calls
* at first String.valueOf(x) to get the printed object's string value,
* then behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>Object</code> to be printed.
*/
public void println(Object x)
String.valueOf(Object)将null转换为“null”:
/**
* Returns the string representation of the <code>Object</code> argument.
*
* @param obj an <code>Object</code>.
* @return if the argument is <code>null</code>, then a string equal to
* <code>"null"</code>; otherwise, the value of
* <code>obj.toString()</code> is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj)