当前位置:网站首页>JVM Zhenxiang series: easy understanding of class files to virtual machines (Part 1)

JVM Zhenxiang series: easy understanding of class files to virtual machines (Part 1)

2020-11-08 20:15:29 Full stack of Java back end technology

Focus on “Java Back end technology stack ”

reply “000” Access to a lot of e-books

know JVM

What is? JVM

JVM Full name Java Virtual Machine, That's what we're familiar with Java virtual machine . It can recognize .class Postfix file , And can parse its instructions , Finally call the function on the operating system , Do what we want .

Maybe some of the kids have learned C++,C++ Developed programs , After compiling into a binary file , It can be executed directly , The operating system is recognizable .

But we drive Java The program is different , Use javac Command compiled .class After the document , The operating system is not recognizable , Need corresponding JVM To do a conversion , The operating system can recognize .

Why can't we be like C++ equally , Run the compiled binary file directly on the operating system ? Instead of building a virtual machine between the program and the operating system ?

This is it. JVM There is something extraordinary about . Everybody knows ,Java It's a very abstract language , Provides a series of features such as automatic memory management . It is unlikely that these features will be implemented directly on the operating system , So we need JVM Do a series of transformations .

You start to learn Java When , I knew there was a Write Once, Run Everywhere. It's just that we wrote a java The file is compiled into .class After the document , It can be run in a variety of systems .

In fact, there is a premise here , We need to install the corresponding JVM, And then our .class The file will run .

such as :Windows The operating system has a corresponding JDK Installed version 、Linux There is a corresponding JDK Installation version, etc .

know JDK

Java Development Kit (JDK) yes Sun company ( Has been Oracle Acquisition ) in the light of Java Developer's software development kit . since Java Since the launch ,JDK Has become the most widely used Java SDK(Software development kit).

After an unofficial investigation , at present JDK8 It's the most user-friendly version .

JDK14 Will be in 4 The month and 7 Received a security update this month , Then from 9 Month due non LTS Version of JDK 15 replace .JDK14 Include 16 New features , for example JDK Flight Recorder Flow of events , Pattern matching and switch expression .

from JDK9 after ,Oracle A new release cycle has been adopted : Every time 6 Release a version of , Every time 3 Released a LTS edition .JDK14 Is the JDK9 The fourth version released later , This version is not LTS edition , Abreast of the times LTS Version is JDK11.

Here is JDK Version

This is just a familiar one , Keep an eye on it JDK Version updates and new features .

Official website address :https://www.oracle.com/java/

About JDK The installation is omitted here .

JDK、JRE、JVM The relationship between

That was already said JDK and JVM Related concepts of ,

JRE The entire Java Runtime Environment, It's based on Java An indispensable running environment for a program written in a language . Through it, too ,Java The developers can release their own programs to users , Let users use .

What is the relationship between the three ?

For the relationship between the three, please see the official website

https://docs.oracle.com/javas...

JDK Contained in the JRE, Also include JDK, and JRE Also include JDK. Range relations :JDK>JRE>JVM

".java" File to ".class" file

javac command

Write a HelloWorld.java file

The content is a Java introduction

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello world");
    }
}

open CMD, Go to current directory , Use command

javac HelloWorld.java

Just compile it HelloWorld.class

The build process

This javac What exactly did the command process do ?

javac This is roughly done behind the scenes

This process

1、 Lexical analysis

Read source code , A byte by byte read , Find out the keywords we have defined ( Such as Java Medium if、else、for、while Other keywords , Identify what if It's a legitimate keyword , Which are not ), This is the process of lexical analysis by lexical analyzer , The result is to find normalized... From the source code Token flow .

2、 Syntax analysis

After analyzing the morphology through the parser Token Stream for parsing , This step checks whether these keyword combinations match again Java language norm ( If in if Is it followed by a Boolean judgment expression ), The result of lexical analysis is to form a consistent Java Abstract syntax tree of language specification .

3、 Semantic analysis

Semantic analysis through semantic analyzer . Speech analysis is mainly to make some difficult to understand 、 Complex grammar into simpler grammar , The result is the simplest grammar ( Such as the foreach convert to for loop , Well, there are notes and so on ), Finally, an annotated abstract syntax tree is formed , This syntax tree is closer to the grammar rules of the target language .

4、 Generated bytecode

Bytecode is generated by bytecode producer , Generate bytecode from annotated syntax abstract tree , That is to transform one data structure into another . Finally, we generate what we want .class file .

Use hexadecimal to see class The contents of the document

All I have to do is Notepad++, Select the text → plug-in unit →Converter→ASCII->HEX

class The beginning of the document is

CAFEBABE

If you want to learn the meaning of hexadecimal bytecode here, you can refer to

https://docs.oracle.com/javas...

-

javap see class The contents of the document

javap yes Java class File resolver , Can decompile ( to javac Decompile the compiled file ), You can also view java Bytecode generated by compiler .

Create a new one User.java Source file , after javac After compiling , Generate User.classs.

package com.tian.demo.test;
public class User {
    private int age = 22;
    private String name = "tian";
    public int addAge() {
        return age = age + 1;
    }
    public static void main(String[] args) {
    }
}

Use javap command

javap -v User.class >log.txt

open log.txt

Classfile /D:/workspace/new/demo/src/main/java/com/tian/demo/test/User.class
  Last modified 2020-11-5; size 441 bytes
  MD5 checksum 2fa72d3f53bd9f138e0bfae82aba67e3
  Compiled from "User.java"
public class com.tian.demo.test.User
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Methodref          #6.#21         // java/lang/Object."<init>":()V
   #2 = Fieldref           #5.#22         // com/tian/demo/test/User.age:I
   #3 = String             #23            // tian
   #4 = Fieldref           #5.#24         // com/tian/demo/test/User.name:Ljava/lang/String;
   #5 = Class              #25            // com/tian/demo/test/User
   #6 = Class              #26            // java/lang/Object
   #7 = Utf8               age
   #8 = Utf8               I
   #9 = Utf8               name
  #10 = Utf8               Ljava/lang/String;
  #11 = Utf8               <init>
  #12 = Utf8               ()V
  #13 = Utf8               Code
  #14 = Utf8               LineNumberTable
  #15 = Utf8               addAge
  #16 = Utf8               ()I
  #17 = Utf8               main
  #18 = Utf8               ([Ljava/lang/String;)V
  #19 = Utf8               SourceFile
  #20 = Utf8               User.java
  #21 = NameAndType        #11:#12        // "<init>":()V
  #22 = NameAndType        #7:#8          // age:I
  #23 = Utf8               tian
  #24 = NameAndType        #9:#10         // name:Ljava/lang/String;
  #25 = Utf8               com/tian/demo/test/User
  #26 = Utf8               java/lang/Object
{
  public com.tian.demo.test.User();
    descriptor: ()V
    flags: ACC_PUBLIC
    Code:
      stack=2, locals=1, args_size=1
         0: aload_0
         1: invokespecial #1                  // Method java/lang/Object."<init>":()V
         4: aload_0
         5: bipush        22
         7: putfield      #2                  // Field age:I
        10: aload_0
        11: ldc           #3                  // String tian
        13: putfield      #4                  // Field name:Ljava/lang/String;
        16: return
      LineNumberTable:
        line 3: 0
        line 4: 4
        line 5: 10
  public int addAge();
    descriptor: ()I
    flags: ACC_PUBLIC
    Code:
      stack=3, locals=1, args_size=1
         0: aload_0
         1: aload_0
         2: getfield      #2                  // Field age:I
         5: iconst_1
         6: iadd
         7: dup_x1
         8: putfield      #2                  // Field age:I
        11: ireturn
      LineNumberTable:
        line 8: 0
  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=0, locals=1, args_size=1
         0: return
      LineNumberTable:
        line 13: 0
}
SourceFile: "User.java"
Magic number and class Document version
Constant pool
Access signs
Class index 、 Parent index 、 Interface index
Field table set
Method table set
Property sheet set

then JVM You can read this User.class File analysis and a series of operations .

That's our Java File to class file .

There will be a series of updates to follow JVM Related articles , Coming soon ~

Recommended reading :

《Java Web Enterprise project actual combat 》.pdf

《MySQL developer SQL Authoritative guide 》.pdf

Official account “Java Back end technology stack ”

Free access 500G The latest learning materials

版权声明
本文为[Full stack of Java back end technology]所创,转载请带上原文链接,感谢