Deep understanding of the Java Class file format (9)

Source: Internet
Author: User


After the first eight blogs about the class file, the content about the class file format is basically finished. This is the last article about the class file format. In this blog, we will explain several attributes of the method. Understanding the content of this blog plays an important role in understanding the JVM execution engine. The content related to the virtual machine execution engine will be covered in the blog behind this column.


In the previous blogs, we know that a method described in the class file will use a method_info. This method_info stores the modifier flag of the method and also references the items in the constant pool. These constant pool data items describe the method names of a method defined in the current class, the descriptor of the method. For more information, see my previous blog: Java Class file format (7 ).


However, method_info does not store the method bytecode, that is, instructions. We know that for a method, as long as it is not abstract (abstract methods in abstract classes or methods in interfaces), there will certainly be instructions. Where are these commands stored? Also, how is the exception processor (try-catch Block) described in the class file? How is the exception thrown by the method declaration described? If you are interested in these questions, you may find the answer in this blog or be inspired.


To ensure the consistency of knowledge, we first briefly review the structure of method_info, because method_info is closely related to this article. The structure of method_info is as follows:



In-depth understanding of the Java Class file format (7) This blog has explained access_flags, name_index, and descriptor_index. They respectively describe the access modifier, method name, and method descriptor of the method. We can see that there are attributes_count and attributes in method_info. That is to say, each method can have another or multiple attributes. The bytecode commands, exception processors, and exceptions thrown by method declarations in the methods described in this article are stored in these attributes.



Code attributes
Code attribute is one of the most important attributes of a method. Because it stores bytecode commands of methods, in addition, it also stores information related to the operand stack and local variables. All non-abstract methods must have a Code attribute in methobutes in method_info. The following is the structure of the Code attribute. In order to intuitively display the inclusion relationship between the Code attribute and method_info, method_info is specially drawn:



The following describes each part of the code attribute in sequence.
Like other attributes described in the previous blog, Attribute_name_indexPoint to a CONSTANT_Utf8_info in the constant pool. This CONSTANT_Utf8_info stores the current attribute name "Code ".
Attribute_lengthThe length of the current Code attribute (excluding the first six bytes) is given ).
Max_stackSpecifies the size of the operand stack to be allocated in the stack frame when the current method is executed by the execution engine.
Max_localsSpecifies the size of the local table to be allocated in the stack frame when the current method is executed by the execution engine. Note that this number is not the number of local variables, because the number is not executed unless a local variable is executed according to the scope of the local variable, the next local variable can reuse the space of the previous local variable (each local variable occupies one or two slots in the local variable table ). The local variables in the method include the parameters of the method, the default parameter this of the method, the variables defined in the method body, and the exception objects in the catch statement. The relevant content about the execution engine will be discussed in the blog below.
Code_lengthSpecifies the length of the bytecode for this method. Each bytecode occupies one byte in the class file.
CodeThe length of the bytecode command is code_length.
Prediction_table_lengthSpecify the size of the exception table
Prediction_tableIs the so-called exception table, it is the description of the try-catch_finally in the method body. Prediction_table can be considered as an array. Each array item is in the prediction_info structure. Generally, each catch block corresponds to an prediction_info. The Compiler may also generate some prediction_info for the current method. The structure of prediction_info is as follows (in order to intuitively display the relationship between prediction_info, prediction_table and Code attributes and draw out the Code attributes, the reader will be more clear about the location and inclusion relationships between data items ):


The following describes the meaning of each field in prediction_info.
Start_pc is the offset from the starting position of the bytecode (Code in the code attribute) to the starting position of the current abnormal processor.
End_pc is the offset from the beginning of the bytecode to the end of the current abnormal processor.
Handler_pc refers to the offset between the first instruction of the exception processor used to handle the exception (catch Block) and the start of the bytecode.
Catch_type is a constant pool index that points to a CONSTANT_Class_info data item in the constant pool. This data item describes the exception type information in the catch Block. This type must be java. lang. Throwable or its subclass.
To sum up, an exception processor (exception_info) means that if the bytecode between the offset from start_pc to end_pc has an exception of the type described by catch_type, then, the execution will jump to the bytecode with the offset of handler_pc. If the catch_type is 0, it means that no constant pool item is referenced (Review, the items in the constant pool are counted from 1), then the prediction_info is used to implement the finally clause.
We have been introducing the Code attribute, but just an episode introduced the details of prediction_info in prediction_table in the Code attribute. Next we will continue to introduce other information in the Code attribute, hoping that readers will not be confused :)
Attributes_countNumber of other attributes in the current Code attribute. Now we know that the attributes in the class will not only appear in the top-level class, but also in field_info and method_info, and even in the attribute.
AttributesIt can be viewed as an array containing other attributes of the Code attribute. Other attributes that can appear in the Code attribute include LineNumberTable and LocalVariableTable. These two attributes are described below.


LineNumberTable attributes
The LineNumberTable attribute exists in the Code attribute, which establishes a link between the bytecode offset and the source Code line number. This attribute is optional and the compiler can choose not to generate this attribute. The structure of this attribute is as follows (the Global Positional relationship is also given, and LineNumberTable is in the lower right corner of the graph ):



Since this attribute is not important, we will briefly describe it here.
The line_number_table section in each LineNumberTable can be considered as an array. Each item in the array is a line_number_info. Each line_number_info Structure describes the relationship between a bytecode and the source code line number. Start_pc is the offset of the bytecode instruction described in line_number_info, and line_number is the line number in the source code corresponding to the bytecode instruction described in line_number_info. It can be seen that each byte code in the method corresponds to a line_number_info, And the line_number in these line_number_info can point to the same row number, because a line of source code can compile multiple bytecode.


LocalVariableTable attributes
The LocalVariableTable attribute establishes the correspondence between local variables in the method and local variables in the source code. This attribute exists in the Code attribute. This attribute is optional and the compiler can choose not to generate this attribute. The structure of this attribute is as follows: (the Global Location relationship graph is also given, and LocalVariableTable is in the lower right corner of the graph)



This attribute is not so important.
The local_variable_table part of each LocalVariableTable can be considered as an array. Each array item is a structure called local_variable_info. This structure describes the variable name and descriptor of a local variable and its correspondence with the source code. The following describes each part of local_variable_info:
Start_pc is the starting bytecode offset of the scope of the local variable corresponding to the current local_variable_info;
Length is the scope of the local variable corresponding to the current local_variable_info. That is, from the bytecode offset start_pc to start_pc + length is the scope of the current local variable;
Name_index points to a CONSTANT_Utf8_info in the constant pool. This CONSTANT_Utf8_info describes the variable name of the current local variable;
Descriptor_index points to a CONSTANT_Utf8_info in the constant pool, which describes the descriptor of the current local variable;
Index describes the position of the current local variable in the table of local variables in the stack frame when this method is executed.
Therefore, each local variable in the method corresponds to a local_variable_info.

Exceptions attributes
First, it must be noted that the Exceptions attribute does not exist in the Code attribute and exists in attributes in method_info. It is equivalent to the Code attribute. This attribute describes the exceptions that may be thrown by the method Declaration, that is, the exception list of the throws declaration after the method definition. Do not confuse it with the exception processor mentioned above. The exception processor describes how the method bytecode handles Exceptions, and the Exceptions attribute describes which Exceptions the method may throw. The following describes the structure of the Exceptions attribute (the lower-left corner is the Exceptions attribute ):


The following describes the information in the Exceptions attribute.
Attribute_name_index and attribute_length are not described in detail. They are the same as other attributes.
Number_of_exceptions is the number of exceptions to be thrown by this method.
Predictions_index_table can be viewed as an array. Each item in this array occupies two bytes. These two bytes are indexes of the constant pool and point to CONSTANT_Class_info in a constant pool. This CONSTANT_Class_info describes the type of the thrown exception.

So far, the attributes related to the method are described. The content of this blog is relatively complex. The following is an instance verification code:
package com.jg.zhang;public class Test {public void test() throws Exception{int localVar = 0;try{Class.forName("com.jg.zhang.Person");}catch(ClassNotFoundException e){throw e;}finally{System.out.println(localVar);}}}

Decompile the test method section (information such as the constant pool is omitted ):
  public void test() throws java.lang.Exception;    flags: ACC_PUBLIC    Exceptions:      throws java.lang.Exception    Code:      stack=2, locals=4, args_size=1         0: iconst_0         1: istore_1         2: ldc           #18                 // String com.jg.zhang.Person         4: invokestatic  #20                 // Method java/lang/Class.forName:(Ljava/lang/String;)Ljava/lang/Class;         7: pop         8: goto          24        11: astore_2        12: aload_2        13: athrow        14: astore_3        15: getstatic     #26                 // Field java/lang/System.out:Ljava/io/PrintStream;        18: iload_1        19: invokevirtual #32                 // Method java/io/PrintStream.println:(I)V        22: aload_3        23: athrow        24: getstatic     #26                 // Field java/lang/System.out:Ljava/io/PrintStream;        27: iload_1        28: invokevirtual #32                 // Method java/io/PrintStream.println:(I)V        31: return      Exception table:         from    to  target type             2     8    11   Class java/lang/ClassNotFoundException             2    14    14   any      LineNumberTable:        line 7: 0        line 11: 2        line 13: 8        line 15: 12        line 16: 14        line 17: 15        line 18: 22        line 17: 24        line 20: 31      LocalVariableTable:        Start  Length  Slot  Name   Signature               0      32     0  this   Lcom/jg/zhang/Test;               2      30     1 localVar   I              12       2     2     e   Ljava/lang/ClassNotFoundException;


By analyzing the decompilation results based on the above explanations and illustrations, we can see that all the results are method_info, And the access Flag Information starts at method_info. Then there is the Exceptions attribute of method_info. The attributes below are the Code attributes. The Code attributes include bytecode, exception processor, LineNumberTable attributes, and LocalVariableTable attributes.
Since most of the content in this blog is related to methods, it will be directly or indirectly related to method_info and finally provide a global image. In this way, the readers will be clear, A complete method is described in the class file. Due to complexity, references to the constant pool in these attributes or other data items are not drawn:








Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.