gpt4 book ai didi

java - InputStream类型的System.in如何初始化?

转载 作者:行者123 更新时间:2023-12-02 04:40:09 25 4
gpt4 key购买 nike

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

static InputStream in;


因此,如果我们希望代码 System.in.read()工作,则必须初始化变量 in

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

最佳答案

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

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


打印(对我来说):

java.io.BufferedInputStream


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

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


打印(再次对我而言):

java.io.FileInputStream


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

通过搜索对 FileDescriptor.in的引用,我找到了初始化System.in的代码:在私有静态方法 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可能由本机代码调用,因为似乎没有对其的引用。

关于java - InputStream类型的System.in如何初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56523171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com