4 ms·
Reminds me of jwz's Java doc on the topic of final variables, and how the access is restricted by compiler convention, not in the JVM: System.in, out and e
by zachbeane 16y ago
Reminds me of jwz's Java doc on the topic of final variables, and how the access is restricted by compiler convention, not in the JVM:
System.in, out and err (the stdio streams) are all final
variables. They didn't used to be, but some clever applet-writer
realized that you could change them and start intercepting all output
and do all sorts of nasty stuff. So, the whip-smart folks at Sun went
and made them final. But hey! Sometimes it's okay to change them! So,
they also added System.setIn, setOut, and setErr methods to change
them!
``Change a final variable?!'' I hear you cry. Yep. They sneak in
through native code and change finals now. You might think it'd give
'em pause to think and realize that other people might also want to
have public read-only yet privately writable variables, but no.
Oh, but it gets even better: it turns out they didn't really have to
sneak in through native code anyway, at least as far as the JVM is
concerned, since the JVM treats final variables as always writable to
the class they're defined in! There's no special case for
constructors: they're just always writable. The javac compiler, on the
other hand, pretends that they're only assignable once, either in
static init code for static finals or once per constructor for
instance variables. It also will optimize access to finals, despite
the fact that it's actually unsafe to do so.
- bobbyi 16y ago> some clever applet-writer realized that you could change them and start intercepting all output and do all sorts of nasty stuff. Can someone explain how this worked? What does he mean by "intercepting all output"?
- btilly 16y agoReplace System.out with an object that responds to all of the same methods, but which does something clever with them. For instance one that adds timestamps on output, logs stuff somewhere, filters, etc. This is a very powerful trick. However the downside is that it is in the category of things where only one person gets to be clever. Because the second person to replace that object breaks the first. So they decided to discourage that.