System.out 被声明为 static final 并用 null 初始化? [英] System.out is declared as static final and initialized with null?

查看:12
本文介绍了System.out 被声明为 static final 并用 null 初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我浏览 System.class 时,我发现了一些对我来说很奇怪的东西.当您查看 System.in, System.out, System.err 的声明时,这些被标记为 final static 但也被初始化为 null

When I was going through the System.class I found something which seemed strange to me. When you look at declaration of System.in, System.out, System.err these are decalred as final static but also initialized with null

public final static InputStream in = null;  
public final static PrintStream out = null;  
public final static PrintStream err = null;

既然 final 只能初始化一次,那么如何管理这些?
当我们使用 System.out.print("..."); 很明显 out 不是 null 而是一个 final static 怎么不是 null ?

Since final can be initialized only once then how these are getting managed ?
When we use System.out.print("..."); It is obvious that out is not null but being a final static how it is not null ?

那么谁能解释一下已经声明为 final 的 out 是如何初始化的?

So can any one explain that how out is initialized which is already declared final ?

推荐答案

它在静态初始化程序中使用本机代码进行初始化.在 System.java 的顶部,您有:

It is initialized with native code in a static initializer. At the top of System.java you have:

/* register the natives via the static initializer.
 *
 * VM will invoke the initializeSystemClass method to complete
 * the initialization for this class separated from clinit.
 * Note that to use properties set by the VM, see the constraints
 * described in the initializeSystemClass method.
 */
private static native void registerNatives();
static {
    registerNatives();
}

registerNatives() 方法将初始化 in/out/err - 它是在本机代码中进行的 - 本机代码几乎可以做任何它想做的事情,并且不限于所有的 java 语言规则.(虽然你也可以通过反射在 Java 中设置一个已经初始化的 final 字段)

The registerNatives() method will initialize in/out/err - and it's doing so in native code - native code can pretty much do whatever it want and are not limited to all of the java language rules. (Though you could get around setting an already initialized final field in Java via reflection too)

这篇关于System.out 被声明为 static final 并用 null 初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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