簡體   English   中英

為什么toString()在一個Object實例(null)上沒有拋出NPE?

[英]Why toString() on an Object instance (which is null) is not throwing NPE?

考慮下面一個:

Object nothingToHold = null;

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

在這里,Sysout必須期待String。 因此必須在實例上調用toString()。

那么為什么null.toString()工作得很棒? Sysout會照顧這個嗎?

編輯:其實我用StringBuilder的append()看到了這個奇怪的東西。 所以嘗試了Sysout。 兩者的行為方式相同。 那個方法也在照顧嗎?

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)

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)

PrintStream#println(Object s)方法調用PrintStream#print(String s)方法,該方法首先檢查參數是否為null ,如果是,則只設置"null"以打印為普通String

但是,傳遞給.print()方法的是"null"作為String ,因為String.valueOf(String s)在調用.print()方法之前返回"null"

public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
}

這是println()文檔

打印一個字符串,后跟換行符。 使用在構造此流期間選擇的編碼將字符串轉換為字節數組。 然后使用write(int)將字節寫入目標流。

如果發生I / O錯誤,則此流的錯誤狀態將設置為true。

NULL可以轉換為字節。

    Object nothingToHold = null;
   System.out.println(nothingToHold != null ? nothingToHold : "null String or any thing else");

如果nothingToHold(Object)不等於null,這將顯示輸出,否則它將消息打印為“null String或any thing”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM