Write the JVM search class file with Go

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Because of the encounter go, the charm of go to be impressed, slowly will happen the following story

Java class loading mechanism

The role of the Java ClassLoader to load the class file into memory. From the Java Developer's point of view, the class loader can be divided into three types:

    • Start class loader (Bootstrap ClassLoader): Load <JAVA_HOME>/jre/lib the jar under
    • Extension class loader (Extension ClassLoader): Loading <JAVA_HOME>/jre/lib/ext/ the jar under
    • Application class loader (application ClassLoader): Load user-written class

Most loaders use, the 双亲委派模型 parent delegation Model works by: If a classloader receives a request from the ClassLoader, it does not attempt to load the class itself, but instead delegates the request to the parent ClassLoader, which is the case for each level of the ClassLoader. So all load requests should eventually be routed to the top-level startup class loader, and the child loader will attempt to load itself only when the parent loader has feedback that it cannot complete the load request (its search scope does not find the desired class).


Class loading flowchart. jpg

Implementation ideas

    • Set command-line arguments, specifying the path
    • Implementing the Classpath: Starting the ClassLoader, extending the ClassLoader, and the Application class loader
    • Abstract the classpath, three as its subclasses

Encoding process

The coding process is introduced from three aspects, the first is the engineering catalogue, so that readers can see clearly. Second, the effect of the operation, the reader can be implemented according to the effect of the search class file, choose whether to continue to watch. Source, please go to the portal.

    • Project Catalogue
    • Run effect
    • Code implementation

Project Catalogue

    • Gopath: Code Storage area (workspace)
    • GOPATH/SRC: The area where the source code is stored
    • Jvmgo: Project Name
    • CH02: Sub-file
    • ch02/classpath/: This time the main code written

Project02.png

Run effect

ch02/ go build -o readClass generate executable file under current directory under compile:readClass

Validation is loaded by the startup class or extension ClassLoader, which java.lang.Object -Xjre is a predefined command-line argument, "/home/sprint/java/utils/jdk1.8.0_91/jre" specifies the JRE path, as follows:


02_result_01.png

Verify that the class is loaded through the application ClassLoader ch02/Test (its own classes), and if you do not specify a path, the default current path. -cpis a predefined command-line argument, "" represents the current directory, as follows:


02_result_02.png

Code implementation

    • terminal.gopre-defined Xjre command-line arguments in
//定义Termial结构体type Terminal struct {    //...省略字段,    XjreOption  string // 添加XjreOption字段}func parseTerminal() *Terminal {    terminal := &Terminal{}    //省略部分代码...    flag.StringVar(&terminal.XjreOption, "Xjre", "", "path to jre")    flag.Parse()    //省略部分代码...    return terminal}
    The
    • Write classpath and its subclasses
      Total Classpath contains: Starts the ClassLoader path, extends the ClassLoader path, and the application class loader path. Under ch02/classpath/, write classpath.go , and define the Classpath as follows:

        type classpath struct {//Start class loader Bootclasspath Entry//Extension class loader Extclasspath Entry//Application loader Userclasspath Entry}  

      Each kind of loader has the same method, at which point an interface is defined to open Represents a class path entry. Under ch02/classpath/, write the entry.go file definition entry interface:

        Type entry  interface {//is responsible for finding and loading class ReadClass (ClassName string) ([]byte, Entry, error)//go function or method run returns multiple values//similar to ToString () string () string}  

      direntry Rep: Application class loader for loading class in file directory. ZipEntry represents: Applies the startup class and the extension ClassLoader for loading the Jar/zip file. compositeentry and wildcardentry represent: collections of entry. Under ch02/classpath , create a entry_dir.go , entry_zip.go , entry_composite.go , entry_wildcard.go file Implementation entry interface. Go's implementation of the interface is different from Java, want to experience the words, hands-on implementation, experience the charm of Go! Due to the length of consideration, so the implementation of the interface is not affixed to the code, the specific source please go to the portal

    • Test execution
      After writing the above code, change ch02/main.go the STARTJVM () function to test.
func startJVM(terminal *Terminal) {    cp := classpath.Parse(terminal.XjreOption, terminal.cpOption)    fmt.Printf("classpath:%v class:%v args:%v\n",        cp, terminal.class, terminal.args)    className := strings.Replace(terminal.class, ".", "/", -1)    classData, _, err := cp.ReadClass(className)    if err != nil {        fmt.Printf("Could not find or load main class %s\n", terminal.class)    }    fmt.Printf("class data:%v\n", classData)}

When everything is ready, the ch02 executable file is generated by typing under the file go build -o readClass readClass . Then follow the command line in "Run" to execute the test!

Summary and statement: While learning more about Java virtual machines, learn go. Knowledge mainly comes from Gitbook (address below) and Zhang Xiohong teacher's "DIY Java Virtual machine", my source code and the source of the book is slightly different.

Reference documents

    • Write your own Java Virtual machine
    • Https://github.com/astaxie/build-web-application-with-golang
    • https:// Github.com/zhaohuxing/jvmgo

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.