日期:2014-05-20  浏览次数:20856 次

Java io 中关于System.in的一个小问题

public class test {
public static void main(String[]args) throws Exception{
InputStream in = System.in;
System.out.println(in);
}
}


跟踪源代码发现:
System.in 就是public final static InputStream in = nullInputStream();
而nullInputStream();的源代码是:

private static InputStream nullInputStream() throws NullPointerException {
if (currentTimeMillis() > 0) {
    return null;
}
throw new NullPointerException();
    }

显然,不出意外是返回null,且System.in 不是native!
为什么System.out.println(in);输出的不是null而是java.io.BufferedInputStream@c17164 ?
---------------
菜鸟求教 !

------解决方案--------------------
我用的是java7,代码跟你的不太一样

    private static native void registerNatives();
    static {
        registerNatives();
    }

这里面调用了setIn或setIn0
------解决方案--------------------
请看上面的注释
    /**
     * 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().

     */
    private static InputStream nullInputStream() throws NullPointerException {
if (currentTimeMillis() > 0) {
    return null;
}
throw new NullPointerException();
    }

------解决方案--------------------
在initializeSystemClass()通过native方法初始化的In
------解决方案--------------------
版主正解   又长见识了