什么是字节码
java bytecode 由单字节(byte)的指令组成,理论上最多支持256个操作码,实际只使用了200左右,其他的保留给调试操作
分类
- 栈操作指令,包括与局部变量交互的指令
- 流程控制指令
- 对象操作指令,包括调用方法
- 算数运算、类型转化指令
最简单的字节码
1 2 3 4 5
| public class HelloByteCode { public static void main(String[] args) { HelloByteCode helloByteCode = new HelloByteCode(); } }
|
javac编译
1 2 3 4 5 6 7 8
| public class HelloByteCode { public HelloByteCode() { }
public static void main(String[] var0) { new HelloByteCode(); } }
|
javap -c 查看字节码
-c:分解方法代码,即显示每个方法具体的字节码
-public | protected | package | private:用于指定显示哪种级别的类成员
-verbose:指定显示更进一步的详细信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| Compiled from "HelloByteCode.java" public class com.qypone.learn.bytecode.HelloByteCode { public com.qypone.learn.bytecode.HelloByteCode(); Code: 0: aload_0 1: invokespecial #1 4: return
public static void main(java.lang.String[]); Code: 0: new #2 3: dup 4: invokespecial #3 7: astore_1 8: return }
|
指令:javap -c -verbose HelloByteCode.class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| Classfile /E:/github/learn/src/main/java/com/qypone/learn/bytecode/HelloByteCode.class Last modified 2021-12-23; size 314 bytes MD5 checksum 2316eef4ab6ce7a12d26b0eaa0f11709 Compiled from "HelloByteCode.java" public class com.qypone.learn.bytecode.HelloByteCode minor version: 0 major version: 55 flags: ACC_PUBLIC, ACC_SUPER Constant pool: #1 = Methodref #4.#13 #2 = Class #14 #3 = Methodref #2.#13 #4 = Class #15 #5 = Utf8 <init> #6 = Utf8 ()V #7 = Utf8 Code #8 = Utf8 LineNumberTable #9 = Utf8 main #10 = Utf8 ([Ljava/lang/String;)V #11 = Utf8 SourceFile #12 = Utf8 HelloByteCode.java #13 = NameAndType #5:#6 #14 = Utf8 com/qypone/learn/bytecode/HelloByteCode #15 = Utf8 java/lang/Object { public com.qypone.learn.bytecode.HelloByteCode(); descriptor: ()V flags: ACC_PUBLIC Code: stack=1, locals=1, args_size=1 0: aload_0 1: invokespecial #1 4: return LineNumberTable: line 3: 0
public static void main(java.lang.String[]); descriptor: ([Ljava/lang/String;)V flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=2, args_size=1 0: new #2 3: dup 4: invokespecial #3 7: astore_1 8: return LineNumberTable: line 5: 0 line 6: 8 } SourceFile: "HelloByteCode.java"
|
示例代码
qypone/blog (github.com)