System.out.println(Object obj)的實現過程

來源:互聯網
上載者:User

在學Java的過程中用的最多的語句恐怕要數System.out.println();這句話了,經常用這句話類比很多事情,那麼這句話是怎樣實現的呢?

首先,System是位於java.lang包中的一個核心類,如果你查看它的定義,你會發現有這樣一行:

public static final PrintStream out;

接著在進一步,點擊PrintStream這個超連結,在METHOD頁面,你會看到大量定義的方法,尋找println,會有這樣一行:

public void println(Object o)

Object並不是一個字串,它列印的到底是什麼呢,看下面這句話:

Prints an object. The string produced by theString.valueOf(Object) method is translated into bytes according to the platform's
default character encoding, and these bytes are written in exactly the manner of thewrite(int) method.

它的意思是它將調用String.valueOf(Object)來擷取對象的字串形式。那麼String.valueOf(Object)又是怎麼處理Object對象的呢,JDK協助文檔的解釋如下:

 If the argument isnull, then a string equal to
"null"; otherwise, the value ofobj.toString() is returned .

即,如果不為空白,它將調用對象的toString()方法。

好了,現在你應該明白為什麼我們要那樣調用了,out是System的一個靜態變數,所以可以直接使用,而out所屬的類有一個println方法。
而最終要列印的字串則是在類中toString方法所定義的。

附:PrintStream類的繼承關係

Class PrintStream

  • java.lang.Object
    • java.io.OutputStream
      • java.io.FilterOutputStream
        • java.io.PrintStream

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.