Source of the problem: I recently read more in-depth JVM-related books and have to feel that the JVM is indeed more profound and hard to understand in many places. I still cannot find any information on the Internet, I found a problem that I couldn't understand when I tried to search online. The results were basically copied from the book, but I still couldn't understand it.
The problem arises: Today we suddenly think of a problem, that is, the class variable, that is, the initialization of static variables. In the past, Fan understood that static variables will be initialized during class loading, but static variables will be initialized before the heap memory is initialized. I know this is the case, but I do not know why. Because class loading involves many steps, such as loading, connection, and initialization. In the past, the meaning of class loading was a bit ambiguous. Is it loading-connection called class loading or loading-connection? We know the class. forname ("classname") and classname. class will return a Class Object of the class (this is not easy to understand, but once you understand this stuff, your understanding of the Java reflection mechanism will go up again ), but what are the differences between the two?
With these two questions, I checked them online and wrote the test code for testing.
1. Define a class myclass: there is an internal, there is a static variable and a static code block.
public class MyClass { static InnerClass in = new InnerClass(); static { System.out.println("static block"); } static class InnerClass { static { System.out.println("inner"); } }}
2. Test code:
@ Suppresswarnings ("all") public class myclasstest {@ test public void testmyclass () {try {Class C1 = myclasstest. class; // No output Class C2 = Class. forname ("chain. myclass "); // output: // inner // static block} catch (exception e) {e. printstacktrace ();}}}
According to the output, we can find that :. class only loads the class into JVM without class initialization, while forname initializes the class (including initializing static variables and static code fast). They all load the class, the only difference is whether or not to initialize class variables. This is the answer to the second question. The answer to the first question is obvious. The loading of static variables I previously understood is actually the result of forname.
Difference between class. forname ("classname") and classname. Class