InputStream类型的System.in如何初始化? [英] How System.in of type InputStream is initialized?

查看:105
本文介绍了InputStream类型的System.in如何初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,在Java中,只能引用抽象类,而不能初始化. InputStream 是一个抽象类,在 System 类中,我注意到以下声明

I know that, in java, abstract class can only be referenced but not initialized. InputStream is an abstract class, and in the System class I noticed the following declaration,

static InputStream in;

因此,如果我们希望代码 System.in.read()起作用,则需要初始化变量 in .

So if we want the code System.in.read() to work, variable in needs to be initialized.

我的问题是java怎么做到的?如果 InputStream 是抽象的,则其他一些子类应该对其进行扩展.默认情况下是哪个班级?

My question is how java does that? If InputStream is abstract, some other subclass should have extend it. Which class is that by default?

推荐答案

幸运的是,很容易检查对象 System.in 所指的类型:

Luckily, it is easy to check the type of object System.in refers to:

System.out.println(System.in.getClass().getName());

打印(对我来说):

java.io.BufferedInputStream

所以它是一个 BufferedInputStream .包装是什么?好吧,

so it's a BufferedInputStream. What is it wrapping? Well,

Field field = FilterInputStream.class.getDeclaredField("in");
field.setAccessible(true);   
System.out.println(field.get(System.in).getClass().getName());

打印(再次对我来说):

prints (again, for me):

java.io.FileInputStream

因此, System.in 是包装在 BufferedInputStream 中的 FileInputStream .如果您认为大多数操作系统将控制台与文件一样对待控制台,则这是有道理的.实际上,此 FileInputStream

So System.in is a FileInputStream wrapped in a BufferedInputStream. This makes sense, if you consider that most operating systems treat the console the same way as a file. In fact, this FileInputStream reads from the "file" referred to by FileDescriptor.in.

通过搜索对 FileDescriptor.in 的引用,我找到了初始化System.in的代码:在私有静态方法 System.initializeSystemClass 中:

By searching for references to FileDescriptor.in, I found the code where System.in is initialized: in the private static method System.initializeSystemClass:

FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
setIn0(new BufferedInputStream(fdIn));
setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));
setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding")));

initializeSystemClass 可能被本机代码调用,因为似乎没有对其的引用.

initializeSystemClass is probably called by native code, as there seem to be no references to it.

这篇关于InputStream类型的System.in如何初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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