为什么PrintStream“out”和InputStream“in”空值? [英] Why are the PrintStream "out" and InputStream "in" null?

查看:222
本文介绍了为什么PrintStream“out”和InputStream“in”空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇,我正在查看 docjar.com 上的一些Java API类的源代码。我看到了java.lang.System类,发现PrintStreamout(即System.out)有以下代码:

Out of curiosity I was looking through the source code for some of the Java API classes found at docjar.com. I saw the java.lang.System class and saw that the PrintStream "out" (i.e., System.out) had the following code:

public final static PrintStream out = null;

并在评论中说:

The "standard" output stream. This stream is already
open and ready to accept output data.

我的问题是,我知道最终的变量无法修改,所以为什么声明为null ?为什么在调用out方法时Java不会抛出NullPointerException? System.in也是如此。

My queston is, I know final variables can't be modified, so why is it null when declared? Why doesn't Java throw a NullPointerException when a method for "out" is called? The same goes for System.in as well.

感谢您的任何澄清。

推荐答案

有一个java.lang.System #registerNatives()本机方法。如果你在jvm源代码中查看它,它会从本机代码中分配sysin,sysout和syserr。在java 7之前,这些声明看起来像 public final static InputStream in = nullInputStream(); 但是我猜他们只是将它改为null而javac中的一些hacks不仅仅是内联它。

There's a java.lang.System#registerNatives() native method. If you look at it in jvm source code, it assigns sysin, sysout, and syserr from native code. Before java 7 these declarations looked like public final static InputStream in = nullInputStream(); but I guess they changed it to be just null with some hacks in javac not to just inline it.

这篇关于为什么PrintStream“out”和InputStream“in”空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆