重置系统输入/输出
如果 System.out 和 System.in 是最终的,这样我们就不会更改它们,那么为什么我们有方法 System.setIn 和 System.setOut 呢?下面的说法不是矛盾吗?
System.in
和System.out
是 无需访问器即可直接访问 方法。但他们并不是直接 可重定向到其他流,因为 它们是最终版
。但我们确实有二传手 方法将它们设置为其他一些 流。
如果它们是最终版本,为什么还要重置它们呢?或者,如果我们需要它们能够重置为其他一些流,为什么要把它们放在第一位?与其直接访问它们,为什么不让用户编写 System.getIn()
和 System.getOut()
呢?
If System.out and System.in are made final so that we do not change them, then why do we have the methods System.setIn
and System.setOut
? Isn't the following statement contradictory?
System.in
andSystem.out
are
accessible directly without accessor
methods. But they are not directly
redirectable to other streams because
they arefinal
. But we do have setter
methods to set them to some other
streams.
If they are final
why even let them be reset? Or if we need them to be able to reset to some other streams why have them final
in first place? Instead of directly accessing them why not let users write System.getIn()
and System.getOut()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您基本上看到的是 Java 早期遗留下来的设计缺陷。这些字段存在于 Java 1.0 中(大概已经是公开的和最终的),当设计者意识到他们需要一种方法来重定向它们时,已经来不及进行更改了,因为这会破坏几乎所有现有的 Java 程序。
Java 的设计始终重视向下兼容性高于一切,因此在 Java 1.1 中,他们添加了 set 方法作为解决方法(使字段非最终只会使设计缺陷变得更糟,至少这样 set 方法可以例如执行以下操作)权限检查)。
You're basically looking at design warts left over from the very early days of Java. The fields existed in Java 1.0 (presumably already public and final), and when the designers realized that they needed a way to redirect them it was too late to change because that would have broken pretty much every single Java program in existence.
Java's design has always valued downwards compatibility above all else, so in Java 1.1 they added the set methods as workaround instead (making the fields non-final would just have made the design flaw worse, at least this way the set methods can e.g. do a permissions check).
setXXX
方法使用一些虚拟机内部的魔法来完成通常不可能完成的事情,即更改最终变量。 (如果最终的流只是真实流的包装器,并且带有可私有更改的包装器,那么没有这样的魔法也是可能的。)与简单的非最终字段相比,这种设计的优点:
与简单的
get
+set
方法(和私有字段)相比:setXXX
方法是后来添加的。The
setXXX
methods are using some VM-internal magic to do things normally not possible, namely changing final variables. (It would be possible without such magic, if the final Streams were only wrappers around the real streams, with privately changable wrapees.)Advantages of this design compared to simple non-final fields:
Compared to simple
get
+set
methods (and private fields):setXXX
methods were added later.过去我在课堂上换进、换出和犯错误时没有遇到任何问题。它在我测试命令行类的某些情况下很有用。我不记得我是使用 set*() 方法还是直接设置流。但这很容易做到。
I've had no problem in the past swapping in classes for in, out and err. It's been useful in some situations where I was testing command line classes. I cannot remember whether I used the set*() method or just directly set the streams. But it was easy to do.