在实际项目开发中,有时为了了解Java编译器内部的一些工作,需要查看Java文件对应的具体的字节码指令集,这里提供两种方式供参考。
一、使用javap命令
javap是JDK提供的一个原生工具,它可以反汇编class文件得到对应的字节码信息,通过调节命令参数,可以获取类的package、fileds和methods等的字节码信息,用的最多的参数也就是-verbose了:
二、Bytecode Outline插件
javap固然可以实现反编译字节码的效果,但是每次都要在命令行中执行,显得有点麻烦,而且通过反编译生成的指令简直就不是给人看的,基本看不懂。这里推荐一款工具Bytecode Outline,它是专门为Eclipse打造的反编译插件,不仅可以查看反编译生成字节码指令集,还提供了所有指令的详细说明。首先在Myeclipse安装该插件需要知道Myeclipse对应的Eclipse版本号,可以查看下面的文件获取:
D:\MyEclipse\MyEclipse 10\readme\readme_eclipse.html
然后是下载安装插件,这里就不介绍了,如果是手动安装,这里提供插件下载地址:http://andrei.gmxhome.de/bytecode/links.html
关于插件的使用,官方文档说的很清楚了,我就不翻译了:
Usage: 1) Window -> Show View -> Other -> Java -> Bytecode to see bytecode of current Java editor/ Class file view. The automatic build for projects should be enabled in order to see generated class files. If "Link with editor" is on, then any selection in Java editor will be followed with selection of appropriated bytecode label, and vice - versa. Note: this bi-directional selection could only works, if your bytecode contains source lines/local variables information. Check your compiler setings, if you are not sure that your compiler generates debug information. If "show raw bytecode" is off, than local variable names will be shown instead of indexes, full qualified names replaced with simply class names, and primitive type abbreviations decoded to readable names. If "show current element only" is on, then only bytecode of current field/method node will be shown (if cursor is placed inside field/method name or body). 2.1) Select two *.class/*.java files -> right click -> Compare with -> Each Other Bytecode 2.2) Select one *.class/*.java file -> right click -> Compare with -> Another Class Bytecode to compare bytecode of selected class files. Compare works also for *.class files included in any referenced *.jar library. "Toggle ASMifier mode on/off" button on both Bytecode Outline and Compare View shows ASMifier java code, that generates selected bytecode. More information about how to use ASMifier you can find here. Note: if ASMifier mode is "on", then selection of java code cannot be folowed by selection of appropriated bytecode instruction, and vice - versa; the "show raw bytecode" action is also meaningless. 3) Window -> Show View -> Other -> Java -> Bytecode reference to see reference documentation to selected bytecode instruction in the bytecode view. This documentation is taken from "Java Virtual Machine" by Jon Meyer & Troy Downing Copyright (c) 1997 by O‘Reilly & Associates, and provided with permission of O‘Reilly Media, Inc. Packaging, cleanup, reformatting and XSL transformation completed by Eugene Kuleshov ([email protected]). 4) Help -> Help contents -> JVM Instruction Reference to see the entire bytecode reference documentation, provided with BCO plugin. |
最后的效果如下所示: