本文介绍了为什么toString()在一个Object实例(null)上没有抛出NPE?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的一个:

Object nothingToHold = null;

System.out.println(nothingToHold);  //  Safely prints 'null'

这里,Sysout必须期待String。
因此必须在实例上调用toString()。

Here, Sysout must be expecting String.So toString() must be getting invoked on instance.

那么为什么null.toString()工作真棒? Sysout是否正在处理这个问题?

So why null.toString() works awesome? Is Sysout taking care of this?

编辑:实际上我在StringBuilder的append()中看到了这个奇怪的东西。所以尝试了Sysout。两者都表现得一样。那个方法也在小心吗?

EDIT : Actually I saw this weird thing with the append() of StringBuilder. So tried with Sysout. Both behave in the same way. So is that method also taking care?

推荐答案

PrintWriter 's println(Object)(当你编写 System.out.println(nothingToHold)时调用的方法)调用 String.valueOf(x),如Javadoc中所述:

PrintWriter's println(Object) (which is the method called when you write System.out.println(nothingToHold)) calls String.valueOf(x) as explained in the 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:

String.valueOf(Object) converts the null to "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)

这篇关于为什么toString()在一个Object实例(null)上没有抛出NPE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 22:23