Sne*_*sne 12 java nullpointerexception
考虑下面一个:
Object nothingToHold = null;
System.out.println(nothingToHold); // Safely prints 'null'
Run Code Online (Sandbox Code Playgroud)
在这里,Sysout必须期待String.因此必须在实例上调用toString().
那么为什么null.toString()工作得很棒?Sysout会照顾这个吗?
编辑:其实我用StringBuilder的append()看到了这个奇怪的东西.所以尝试了Sysout.两者的行为方式相同.那个方法也在照顾吗?
Era*_*ran 18
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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
该PrintStream#println(Object s)方法调用该PrintStream#print(String s)方法,该方法首先检查参数是否为null,如果是,则设置"null"为打印为plain String.
但是,传递给.print()方法的内容是"null"as String,因为在调用方法之前String.valueOf(String s)返回."null".print()
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
Run Code Online (Sandbox Code Playgroud)