Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

stream

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");
}
like image 333
PrashanD Avatar asked Jun 16 '13 08:06

PrashanD


1 Answers

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.

like image 55
AlexR Avatar answered Sep 22 '22 20:09

AlexR