Java:System.out.println 源码分析


#Java 笔记


2015-01-22

环境:jdk 1.7。

能从System.out.println()字面上看出什么?

首先System是一个类,而且是在JVM启动时候就被导入的。

out是什么?不可能是一个方法,因为它后面没有跟(),所以是一个属性(或者变量),由于System是类,而非对象,所以out是一个static的属性。由于out后面是函数println(),所以out是一个对象或者内部静态类(下文给了一个示例)。out会不会是内部静态类?由于out这一命名形式不合类的命名规范,所以out不是类。最终,out是个对象。

println()是对象out的一个方法。

System.out.println()到底如何工作?

System类是具体是java.lang.Systemout在其中的定义如下:

public final static PrintStream out = null;

JVM在加载System类的时候会有一个初始化的过程。在In Java, how does System.out.println() work?

When the JVM is initialized, the method initializeSystemClass() is called that does exactly what it’s name says – it initializes the System class and sets the out variable. The initializeSystemClass() method actually calls another method to set the out variable – this method is called setOut().

然后,我们关注一下PrintStream类,该类具体是java.io.PrintStream

先看一下println(char[] x)做了什么:

public void println(char x[]) {
    synchronized (this) {
        print(x);
        newLine();
    }
}

由于有synchronized,所以不用担心print的内容会被其他print的内容打断。

然后,看一下print(x);是怎么回事:

public void print(char s[]) {
    write(s);
}

然后:

private void write(char buf[]) {
    try {
        synchronized (this) {
            ensureOpen();
            textOut.write(buf);
            textOut.flushBuffer();
            charOut.flushBuffer();
            if (autoFlush) {
                for (int i = 0; i < buf.length; i++)
                    if (buf[i] == '\n')
                        out.flush();
            }
        }
    }
    catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
}

textOutjava.io.BufferedWriter的对象,看不下去了。。。

内部静态类示例

package hellojava;
public class HelloJava {
    
    public static class HiPython {
        public static void hi() {
            System.out.println("hi");
        }
    }
    public static void main(String[] args) {
        HelloJava.HiPython.hi();
    }
}

参考

In Java, how does System.out.println() work?

http://docs.oracle.com/javase/7/docs/api/java/lang/System.html



( 本文完 )