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

查看:131
本文介绍了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 但是最终静态它是如何 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 ?

那么任何人都可以解释如何初始化已经宣布为最终的?

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中设置已经初始化的最终字段)

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天全站免登陆