What are the init and clinit methods in Java

What are init and clinit in Java (prepared to say that these two methods should be added with <>, but I do n’t know why it will be empty as soon as it is added)?
Before describing these two methods in detail, let's take a look at the scene where the friends may actually encounter these two methods:
first, let's talk about the clinit method, when we DEBUG static code blocks. For example, the following question:
Insert picture description here
How much will be output? How many small partners can be tested by themselves. Our concern is that when we DEBUG to 11 lines of code, it will look like this under the DEBUG window: the
Insert picture description here
red marked position is the clinit method.
We can also adjust the code slightly, throw a runtime exception in the staic code block, and look at the stack of exception information. The screenshot is as follows:
Insert picture description here
from the stack information we can see this clinit method more intuitively.
The clinit method is generated by the compiler automatically collecting the assignment actions of all class variables in the class and merging the statements in the static statement block (static {} block). The initialization phase of class loading is the process of executing the class constructor clinit method. We do n’t say much about the specific information about class loading and initialization. If we want to see what this method is, we can start with bytecode. There is a problem), such as using javap -v ClassInitTest.class to get the disassembled bytecode, the screenshot of the method table (the description of the method in the Class file structure) is as follows:
Insert picture description here
So how to prove that this is indeed the clinit method What? We can install jclasslib in idea, the installation method is:
File> Settings> Plugins, search for jclasslib, install and restart after installation. After restarting, open the corresponding java file, select View> Show Bytecode With Jclasslib to open, as follows:
Insert picture description here
The third method (subscript 2) in the Methods in classlib is the clinit method. The corresponding bytecode is shown in the rightmost part of the above figure. Interested partners can check the JVM instruction and keep up with the leftmost part of the java in the above figure. The corresponding source code.
To be continued (the init method is an instance constructor, note that clinit is a class constructor), the init method part will be added later.

Published 14 original articles · won 3 · views 931

Guess you like

Origin blog.csdn.net/sjz88888/article/details/104704452