There is a very common code: System.out.println. This is a very common output statement, but after studying it for a while, I suddenly remembered to look at the source code. The following is the source code:
public final static PrintStream out = null;
out is defined under the System class and has not been instantiated. Out is just a null variable and cannot even be called a static object. However, it can call the println() method under the PrintStream class. This is not Too understanding? May I ask why?
Detailed explanation: Chinese version http://www.cnblogs.com/skywan...
English version based on jdk7 https://luckytoilet.wordpress...
Dear, first of all, when you start your test class, that is, when you instantiate your test class, all the static classes you call will be instantiated first, so in fact, when you execute the System.out.println statement, The methods and properties in the System class have been initialized!
static {
}
The annotation of the above static method says that the initializeSystemClass method will be called for initialization. The setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding"))); in this method should assign a value to out,
private static native void setOut0(PrintStream out) is a native method;
When I saw final static, my first reaction should be that this is a constant, and constants must be initialized. Then I looked for it again, and sure enough
it calls a local method to initialize;
Well, the initialization work done in the initializeSystemClass() function is called after the system thread is initialized. In other words, all static member variables (err out in) are initialized in this function.
For example, this out:
FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));
The setOut0() function is in the native layer , establish a connection between the initialized object and this out in the native layer