Reset System.in/out

If System.out and System.in are made final so that we don’t change them, then why do we have the System.setIn and System.setOut ? Does the following statement contradict?

System.in and System.out are accessible directly without accessing methods. But they are not directly redirected to other threads, because they are final . But we have setter methods to set them for some other threads.

If they are final why even let them reset? Or, if we need them to be able to reset for some other threads, why are they final in the first place? Instead of directly accessing them, why don't users write System.getIn() and System.getOut() ?

+4
source share
3 answers

You basically look at the design of the warts left over from the very beginning of Java. Fields existed in Java 1.0 (supposedly already publicly available and final), and when the designers realized that they needed a way to redirect them, it was too late to change because it would disrupt almost the entire existing Java program.

The Java construct always valued reduced compatibility above everything else, so in Java 1.1 they added dialing methods as a workaround instead (which makes odd fields just worse for design, at least in this way dialing methods can for example do a permission check).

+3
source

The setXXX methods use some internal magic of the VM to perform ordinary actions, and not to modify the final variables. (It would be possible without such magic if the last flows were only wrappers around real flows, with privately changing wrapees.)

The advantages of this design compared to simple unfinished fields:

  • Methods may ask the installed SecurityManager to check whether the caller has the necessary permissions to modify the threads.

Compared to simple get + set methods (and private fields):

  • Shorter to write.
  • More important, as Michael said: compatibility with old code. The setXXX methods were added later.
+1
source

I had no problems with the last replacement in the classes for in, out and err. This was useful in some situations when I tested the command line classes. I don’t remember if I used the set * () method or just installed the threads directly. But it was easy to do.

0
source

Source: https://habr.com/ru/post/1339585/


All Articles