为什么toString()在一个Object实例(null)上没有抛出NPE?

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

PrintWriterprintln(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)

  • 只是要明确`object.toString()`如果对象为null,将保证NPE.自己试试吧.`System.out.println()`适用于对象的引用开头.PrintWriter知道何时传递空引用,因此它将正常传递并打印出"null".但是如果你尝试从`null`调用`toString()`它肯定会抛出NPE. (3认同)

Kon*_*kov 8

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)

  • 所以现在它会调用`String.valueOf`,这就是引入``null'字符串. (2认同)