JVM details-Java source code compilation

Source: Internet
Author: User

Http://blog.csdn.net/larrylgq/article/details/7395261

Java source code-level compilerThe task is to compile the source code that complies with the Java language specification into a class file that complies with the JVM specification, and report errors that do not comply with the Java language specification.

In Sun's JDK, the source code compiler uses javac written in Java.

Javac workflow:

1 parsing (PARSE) and input to the symbol table (enter)

2. annotation Processing)

3. Analysis and code generation

Resolution:

Lexical Analysis: Use the com. Sun. Tools. javac. parser. Token class to convert the code string to the token sequence.

Eg:

Int y = 1;

-> Token. INT (Name: INT)-> token. identifier (Name: Y) + token. eq (Name: =) + token. intliteral (stringval: 1) + token. semi (Name :;))

Syntax analysis: a syntax analyzer with recursive descent and operator priority. It uses the com. Sun. Tools. javac. parser. parser class to generate an abstract syntax tree from the token Sequence Based on the syntax.

Eg:

 

 

Input to symbol table:

The com. Sun. Tools. javac. Comp. Enter Class is used. In this process, the top nodes of the abstract syntax tree of each compilation unit are first put in the list to be processed and processed one by one.

All class symbols are entered into the symbol table of the peripheral scope.

Determine the class parameters (for generic types), supertypes, and interfaces

If you want to add a default constructor

Enter the symbols in the class into the symbol table of the class.

Analyze and check the annotation in the code

 

Annotation Processing: Annotation Processing

Use the com. Sun. Tools. javac. Processing. javacprocessingenvironment class and support custom annotation.

During compilation, lombook will go to the parse and enter step again after compiling the Java file.

 

Annotation (ATTR) and check ):

Is a step of semantic analysis, using the com. Sun. Tools. javac. Comp. ATTR class and COM. Sun. Tools. javac. Comp. Check class

Main functions:

Associate the name, expression, and other elements in the syntax tree with variables, methods, and types.
Check whether the variable has been declared before use
Derivation of type parameters for generic methods
Check type Matching
Constant folding (merge the constant syntax tree)

Data Flow Analysis):

Use the com. Sun. Tools. javac. Comp. Flow class

Check that all statements can be reached

Check whether all checked exceptions are caught or thrown.
Check that all local variables must be assigned a value before use.

Check whether methods with returned values must return deterministic values.

Check the certainty of variables without repeated values

Conversion Type:( Transtypes)

The main function of COM. Sun. Tools. javac. Comp. transtypes is to convert generic Java code into common Java code.

Eg:

List <integer> List = arrays. aslist (1, 2, 3 );
Int I = list. Get (0 );

After conversion:

List list = arrays. aslist (1, 2, 3 );
Int I = (integer) list. Get (0); To ensure the semantics of the generic type, a forced type conversion is added.

 

Remove syntactic sugar:( Lower)

Use the com. Sun. Tools. javac. Comp. Lower class

Eliminate useless code in the form of IF (false) {...}

Rewrite a syntax tree containing syntactic sugar to a syntax tree containing a simple language structure

Eg

Named internal class, anonymous internal Class, Class literal

Automatic packing and unpacking

Assertions

Foreach Loop

Enum or string type switch (java7)

Eg:

List <integer> List = arrays. aslist (1, 2, 3 );
Int I = list. Get (0 );

After conversion:

List list = arrays. aslist (// automatically unboxing
New integer [] {
Integer. valueof (1 ),
Integer. valueof (2 ),
Integer. valueof (3)
}
);
Int I = (integer) list. Get (0). intvalue ();

Generate a class file:( Gen)

Use com. Sun. tool. javac. JVM. gen

Collect the instance Member initializer to the constructor to become <init> ()
Collect static member initializes as <clinit> ()
Generate bytecode from the abstract syntax tree
Traverse the syntax tree in descending order
Perform the final Code Conversion
The string + operation is generated as the stringbuilder operation.
X ++/X -- Optimized to ++ x/-- X when conditions permit
Etc...
Generate a class file from the symbol table
Generate the structure information of the class file
Generate metadata (including constant pool)

Information recorded in the class file:

Structure Information

Class file format version number

Quantity and size of each part

Metadata

Class, the inherited superclass, and the declaration information of the implemented Interface

Domain and method declaration information

Constant pool

The user-defined retentionpolicy is a class or runtime annotation.

Method Information

Bytecode (Program Logic)

Exception processor table

Size of the operand stack and local variable zone

Type record of the operand stack (stackmaptable starts in Java 6)

Symbol Information for debugging (linenumbertable, localvariabletable)

 

Example of a class file:

Import java. Io. serializable;
Public class Foo implements serializable {
Public void bar (){
Int I = 31;
If (I> 0 ){
Int J = 42;
}
}
}

Execute the compilation: javac-G Foo. Java

Execute decompilation: javap-C-S-l-verbose foo

Class declaration:

Public class Foo extends java. Lang. Object implements java. Io. serializable

Source File Name:

Sourcefile: "foo. Java"

Class file structure information:

Minor version: 0
Major version: 50

Constant pool:

Constant pool:
Const #1 = method #3. #19; // Java/lang/object. "<init>" :() V
Const #2 = Class #20; // foo
Const #3 = Class #21; // Java/lang/Object
Const #4 = Class #22; // Java/IO/serializable
Const #5 = asciz <init>;
Const #6 = asciz () V;
Const #7 = asciz code;
Const #8 = asciz linenumbertable;
Const #9 = asciz localvariabletable;
Const #10 = asciz this;
Const #11 = asciz lfoo ;;
Const #12 = asciz bar;
Const #13 = asciz J;
Const #14 = asciz I;
Const #15 = asciz I;
Const #16 = asciz stackmaptable;
Const #17 = asciz sourcefile;
Const #18 = asciz Foo. Java;
Const #19 = nameandtype #5: #6; // "<init>" :() V
Const #20 = asciz Foo;
Const #21 = asciz Java/lang/object;
Const #22 = asciz Java/IO/serializable; // use the * wildcard when introducing the package. From the class file, there is no difference, however, using wildcards increases the possibility of name conflicts in the source code.

Method metadata:

Public Foo ();
Signature: () V
Linenumbertable:
Line 2: 0
Localvariabletable:
Start length slot name Signature
0 5 0 this lfoo;
Code:
Stack = 1, locals = 1, args_size = 1

Bytecode:

0: aload_0
1: invokespecial #1; // method Java/lang/object. "<init>" :() V
4: Return

Method metadata:

Public void bar ();
Signature: () V
Linenumbertable:
Line 4: 0
Line 5: 3
Line 6: 7
Line 8: 10
Localvariabletable: // The parameter name and local variable name are stored in localvariabletable. The returned Attribute Table is associated with the method body, but the method of the interface has no method body,
Start length slot name signature // Therefore, ASM cannot obtain the parameter name from methods of the interface type.
10 0 2 J I
0 11 0 this lfoo;
3 8 1 I
Stackmaptable: number_of_entries = 1
Frame_type = 252/* append */
Offset_delta = 10
Locals = [int]
Code:
Stack = 1, locals = 3, args_size = 1

Bytecode:

0: bipush 31
2: istore_1
3: iload_1
4: ifle 10
7: bipush 42
9: istore_2
10: Return

 

Comparison between class files and JDK versions:

JDK version class file version (Major. Minor)
1.0 -------- 45.3
1.1 -------- 45.3
1.2 -------- 46.0
1.3 -------- 47.0
1.4 -------- 48.0
5 -------- 49.0
6 -------- 50.0
7 -------- 51.0

 

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.