安装了JDK后,你在JDK目录下可以发现一个 src.zip 或者 src.jar,不管是什么扩展名,都是 zip 格式的压缩包,解压开后在 java/lang 里可以找到 System.java,这就是源码。
源码中有如下对 in, out 和 err 的申明:
public final static InputStream in = nullInputStream();
public final static PrintStream out = nullPrintStream();
public final static PrintStream err = nullPrintStream();
private static PrintStream nullPrintStream() throws NullPointerException {
if (currentTimeMillis() > 0)
return null;
throw new NullPointerException();
}
也许这里看不出来为什么要这样做,所以我们看上面的注释:
/**
* The following two methods exist because in, out, and err must be
* initialized to null. The compiler, however, cannot be permitted to
* inline access to them, since they are later set to more sensible values
* by initializeSystemClass().
*/
注释中说 in, out 和 err 都必须初始化为 null,之后由 initializeSystemClass() 设置值,所以再去阅读这个方法,大概在 1029 行左右。其中有这样几句:
public final class System {
......
public final static InputStream in = nullInputStream();
public final static PrintStream out = nullPrintStream();
......
private static InputStream nullInputStream() throws NullPointerException {
if (currentTimeMillis() > 0)
return null;
throw new NullPointerException();
}
private static PrintStream nullPrintStream() throws NullPointerException {
if (currentTimeMillis() > 0)
return null;
throw new NullPointerException();
}
......