编程知识 cdmana.com

Implementation of handwritten JVM on Java command line

We know , We compile .java And run .class When you file , Need some java command , Such as the simplest helloworld Program .
 Insert picture description here
It's best not to add a package name to the program here , Because if the package name is added, the compilation and operation need to be changed .

Look at the order here .javac For compiling commands , We know java It's a compilation , Run anywhere . The compiler here means javac, about java The procedure is .java file , First use javac Compile into bytecode . And then the bytecode (.class file ) Put it in java Running in virtual machine , That is, in the figure above java HelloWorld,java The virtual machine translates the bytecode into machine instructions on the corresponding machine , Then the machine executes the specific machine instructions . in other words java Programmers are directly associated with java Virtual machine interaction , Introduction and machine interaction . So what virtual machines do is java command , So what we're going to do is java The function of this command is .

So we set our first goal as , Implement a simple command line . That is, we can input some content through the command line , After the virtual machine reads, it can give certain feedback .

GO There are two command line related packages in the language , Namely os and flag(java Class library in Chinese is jar File import ,go In the form of packages ).

First, in the GOPATH In the catalog src Create a new jvmgo Folder as our workspace Directory ,jvmgo There's a new one ch01 For our first target source folder , add to cmd.go file . Insert picture description here
stay cmd.go Enter the following code

package main

import "flag"
import "fmt"
import "os"

// Definition Cmd Structure 
type Cmd struct{
    helpFlag     bool
    versionFlag     bool
    cpOption     string
    class     string
    args     []string
}

// Parsing command line arguments 
func parseCmd() *Cmd {
    cmd:=&Cmd{}

    // take printUsage Function to flag.Usage
    flag.Usage=printUsage
    // Set various parsing options 
    flag.BoolVar(&cmd.helpFlag, "help", false, "print help message")
    flag.BoolVar(&cmd.helpFlag, "?", false, "print help message")
    flag.BoolVar(&cmd.versionFlag, "version", false, "print version and exit")
    flag.StringVar(&cmd.cpOption, "classpath", "", "classpath")
    flag.StringVar(&cmd.cpOption, "cp", "", "classpath")
    // After all options are set, they are called flag.Parse Parse all options , If Parse Failure , Call flag.Usage Print help 
    flag.Parse()

    // call flag.Args Function captures unresolved parameters , The first parameter is the main class name , The following is the parameter passed to the main class 
    args:=flag.Args()
    if len(args)>0{
        cmd.class=args[0]
        cmd.args=args[1:]
    }
// Join in Java Development and exchange :756584822 Blow water and chat together 
    return cmd
}

func printUsage() {
    fmt.Printf("Usage:%s[-options] class [args...]\n",os.Args[0])
}


The first line is package name ,main package , Then three packages were introduced os,flag,fmt.os and flag All the packages needed to handle the command line ,fmt Be similar to C Linguistic printf and scanf Etc IO. And then we define a structure Cmd, Use this data structure to format and store the input command line information .helpFlag The parameter is whether the command line requests help,versionFlag The parameter is whether the command line requests version,cpOption Passed in for the command line classpath That's the goal .class File folder ,class Passed in for the command line .class file name ( barring .class),args Other parameters passed in for the command line .

And then there was a parseCmd function (go There are two kinds of language: function and method , Method calls require receiver, Function calls do not require ), The return value is *Cmd, Used to resolve cmd Parameters transmitted . This function first declares a cmd And give this cmd A new assignment Cmd object .go In language “:=” Declare and assign values to , and "=" Assign to . The first printUsage Assign a function of to flag.Usage, And then call flag Set the options that need to be resolved , It's all parsed , call Parse Function parses all options . If the parsing is successful, it will end , If parsing fails, call printUsage Print to console .

flag.Args You can capture other unresolved parameters . After the above analysis is successful , The first parameter is the main class name , The rest is the parameters passed to the main class .

Tool class writing completed , The next one is the main function . First, the main function code :

package main
// Join in Java Development and exchange :756584822 Blow water and chat together 
import "fmt"

func main() {
    // call parseCmd Parsing command line arguments 
    cmd:=parseCmd()

    if cmd.versionFlag{
        // Input -version Options 
        fmt.Println("version 0.0.1")
    }else if cmd.helpFlag||cmd.class==""{
        // Input -help Options 
        printUsage()
    }else{
        // start-up jvm
        stratJVM(cmd)
    }
}

func stratJVM(cmd *Cmd){
    fmt.Printf("classpath:%s class:%s args:%v\n",
        cmd.cpOption,cmd.class,cmd.args)
}

Follow java similar , stay go Inside main It's a special bag ,go The entry point of the program is main function , But it doesn't take any parameters , There can be no return value .main Function calls first parseCmd Parsing command line arguments , If it is -version The version number is returned , If it is -help Then return help information , If it's anything else, start jvm, Here's some output information “ pretend ” Launched the jvm, real jvm The code will be followed by .

thus , The parsing of the command line is complete . Let's show you the structure of the entire working directory , Otherwise, errors will occur when compiling and running later .

 Insert picture description here
Our working directory is D On the plate JVM Inside goWorkSpace, Next src,jvmgo,ch01,ch01 It contains our go file .

Let's test it , Open a command line , Input go install jvmgo\ch01. This command is to use go.exe Come on install file , This file exists in GOPATH The folder below (jvmgo\ch01 in ), The result is shown in Fig. :
   Insert picture description here
  And then in the workspace (GOPATH) Of bin There is one more in the folder ch01.exe.
 Insert picture description here
Open the command line here . You can do something : Insert picture description here
  Come here , Our command line tool is done , Although there is no real virtual machine design involved , But it's also an important step in running a virtual machine , The design of virtual machine will be introduced gradually later .




 Insert picture description here
image

newest 2020 Organize and collect some high frequency interview questions ( It's all documented ), There are a lot of dry goods , contain mysql,netty,spring, Threads ,spring cloud、jvm、 Source code 、 The algorithm is explained in detail , There's also a detailed learning plan , Interview questions, etc ,
If you need to get this content, please add Q Your appearance :
756584822

版权声明
本文为[osc_ 5w65ebjo]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201225074802301x.html

Scroll to Top