Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

In the System.java source, the standard input, output and error streams are declared final and initialized null?

public final static InputStream in = null;
public final static PrintStream out = null;
public final static PrintStream err = null;

But as we very well know, these streams are connected to the console by default and already open. There are also methods in the System class setIn(), setOut, and setErr() to redirect the streams. How is any of this possible when they have been declared final and set to the initialization value null?

I compiled the following code, set a breakpoint at the call to println() and debugged using netbeans. My objective was to determine exactly when the variable System.in is initialized to the standard output by stepping into the source. But it seems that the output stream out is already initialized by the time the main method is called.

public static void main(String[] args) {
    System.out.println("foo");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is done in order to prevent "hacking". These fields can be changed only by appropriate setters that call native methods

private static native void setIn0(InputStream in);
private static native void setOut0(PrintStream out);
private static native void setErr0(PrintStream err);

Native methods can do everything including changing final fields.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...