为了更好的学习jvm阅读过《Java虚拟机规范》、《自己动手写Java虚拟机》,尤其是《自动动手写java虚拟机》可以更加清晰的看到全貌。对于程序开发者来说学习一个新东西最好事必躬亲,亲力亲为的做出一些demo,只有输出了结果心里才踏实。
本章节主要是通过编写java代码,从main方法入口进行获取指令。例如;-version
itstack-demo-jvm-01 ├── pom.xml └── src └── main │ └── java │ └── org.itstack.demo.jvm │ ├── Cmd.java │ └── Main.java └── test └── java └── org.itstack.demo.test └── HelloWorld.java 复制代码
pom.xml
<!-- 命令行参数解析器 --> <dependency> <groupId>com.beust</groupId> <artifactId>jcommander</artifactId> <version>1.72</version> </dependency> 复制代码
Cmd.java
package org.itstack.demo.jvm; import com.beust.jcommander.JCommander; import com.beust.jcommander.Parameter; import java.util.List; /** * http://www.itstack.org * create by fuzhengwei on 2019/4/24 */ public class Cmd { @Parameter(names = {"-?", "-help"}, description = "print help message", order = 3, help = true) boolean helpFlag = false; @Parameter(names = "-version", description = "print version and exit", order = 2) boolean versionFlag = false; @Parameter(names = {"-cp", "-classpath"}, description = "classpath", order = 1) String classpath; @Parameter(description = "main class and args") List<String> mainClassAndArgs; boolean ok; String getMainClass() { return mainClassAndArgs != null && !mainClassAndArgs.isEmpty() ? mainClassAndArgs.get(0) : null; } List<String> getAppArgs() { return mainClassAndArgs != null && mainClassAndArgs.size() > 1 ? mainClassAndArgs.subList(1, mainClassAndArgs.size()) : null; } static Cmd parse(String[] argv) { Cmd args = new Cmd(); JCommander cmd = JCommander.newBuilder().addObject(args).build(); cmd.parse(argv); args.ok = true; return args; } } 复制代码
Main.java
package org.itstack.demo.jvm; /** * http://www.itstack.org * create by fuzhengwei on 2019/4/24 * program arguments:-version */ public class Main { public static void main(String[] args) { Cmd cmd = Cmd.parse(args); if (!cmd.ok || cmd.helpFlag) { System.out.println("Usage: <main class> [-options] class [args...]"); return; } if (cmd.versionFlag) { System.out.println("java version /"1.8.0/""); return; } startJVM(cmd); } private static void startJVM(Cmd cmd) { System.out.printf("classpath:%s class:%s args:%s/n", cmd.classpath, cmd.getMainClass(), cmd.getAppArgs()); } } 复制代码
java version "1.8.0" 复制代码
微信搜索「 bugstack虫洞栈 」公众号,关注后回复「 用Java实现jvm源码 」获取本文源码&更多原创专题案例!