JVM _03 类加载与字节码技术(详解类文件结构和字节码指令)

JVM _03 类加载与字节码技术(详解类文件结构和字节码指令)

类加载与字节码技术

a.png

1. 类文件结构

一个简单的 HelloWorld.java

// HelloWorld 示例


// HelloWorld 示例

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("hello world");
    }
}
复制代码

执行javac -parameters -d . HellowWorld.java

编译为 HelloWorld.class 后是这个样子的:

[root@localhost ~]# od -t xC HelloWorld.class

0000000 ca fe ba be 00 00 00 34 00 23 0a 00 06 00 15 09

0000020 00 16 00 17 08 00 18 0a 00 19 00 1a 07 00 1b 07

0000040 00 1c 01 00 06 3c 69 6e 69 74 3e 01 00 03 28 29

0000060 56 01 00 04 43 6f 64 65 01 00 0f 4c 69 6e 65 4e

0000100 75 6d 62 65 72 54 61 62 6c 65 01 00 12 4c 6f 63

0000120 61 6c 56 61 72 69 61 62 6c 65 54 61 62 6c 65 01

0000140 00 04 74 68 69 73 01 00 1d 4c 63 6e 2f 69 74 63

0000160 61 73 74 2f 6a 76 6d 2f 74 35 2f 48 65 6c 6c 6f

0000200 57 6f 72 6c 64 3b 01 00 04 6d 61 69 6e 01 00 16

0000220 28 5b 4c 6a 61 76 61 2f 6c 61 6e 67 2f 53 74 72

0000240 69 6e 67 3b 29 56 01 00 04 61 72 67 73 01 00 13

0000260 5b 4c 6a 61 76 61 2f 6c 61 6e 67 2f 53 74 72 69

0000300 6e 67 3b 01 00 10 4d 65 74 68 6f 64 50 61 72 61

0000320 6d 65 74 65 72 73 01 00 0a 53 6f 75 72 63 65 46

0000340 69 6c 65 01 00 0f 48 65 6c 6c 6f 57 6f 72 6c 64

0000360 2e 6a 61 76 61 0c 00 07 00 08 07 00 1d 0c 00 1e

0000400 00 1f 01 00 0b 68 65 6c 6c 6f 20 77 6f 72 6c 64

0000420 07 00 20 0c 00 21 00 22 01 00 1b 63 6e 2f 69 74

0000440 63 61 73 74 2f 6a 76 6d 2f 74 35 2f 48 65 6c 6c

0000460 6f 57 6f 72 6c 64 01 00 10 6a 61 76 61 2f 6c 61

0000500 6e 67 2f 4f 62 6a 65 63 74 01 00 10 6a 61 76 61

0000520 2f 6c 61 6e 67 2f 53 79 73 74 65 6d 01 00 03 6f

0000540 75 74 01 00 15 4c 6a 61 76 61 2f 69 6f 2f 50 72

0000560 69 6e 74 53 74 72 65 61 6d 3b 01 00 13 6a 61 76

0000600 61 2f 69 6f 2f 50 72 69 6e 74 53 74 72 65 61 6d

0000620 01 00 07 70 72 69 6e 74 6c 6e 01 00 15 28 4c 6a

0000640 61 76 61 2f 6c 61 6e 67 2f 53 74 72 69 6e 67 3b

0000660 29 56 00 21 00 05 00 06 00 00 00 00 00 02 00 01

0000700 00 07 00 08 00 01 00 09 00 00 00 2f 00 01 00 01

0000720 00 00 00 05 2a b7 00 01 b1 00 00 00 02 00 0a 00

0000740 00 00 06 00 01 00 00 00 04 00 0b 00 00 00 0c 00

0000760 01 00 00 00 05 00 0c 00 0d 00 00 00 09 00 0e 00

0001000 0f 00 02 00 09 00 00 00 37 00 02 00 01 00 00 00

0001020 09 b2 00 02 12 03 b6 00 04 b1 00 00 00 02 00 0a

0001040 00 00 00 0a 00 02 00 00 00 06 00 08 00 07 00 0b

0001060 00 00 00 0c 00 01 00 00 00 09 00 10 00 11 00 00

0001100 00 12 00 00 00 05 01 00 10 00 00 00 01 00 13 00

0001120 00 00 02 00 14

根据 JVM 规范,类文件结构如下

ClassFile {

    u4            magic;
    u2            minor_version;
    u2            major_version;
    u2            constant_pool_count;
    cp_info            constant_pool[constant_pool_count-1];
    u2            access_flags;
    u2            this_class;
    u2            super_class;
    u2            interfaces_count;
    u2            interfaces[interfaces_count];
    u2            fields_count;
    field_info            fields[fields_count];
    u2            methods_count;
    method_info            methods[methods_count];
    u2            attributes_count;
    attribute_info            attributes[attributes_count];
}
复制代码

1.2 魔数

0~3 字节,表示它是否是【class】类型的文件

0000000 ca fe ba be 00 00 00 34 00 23 0a 00 06 00 15 09

1.2 版本

4~7 字节,表示类的版本 00 34(52) 表示是 Java 8

0000000 ca fe ba be 00 00 00 34 00 23 0a 00 06 00 15 09

1.3 常量池

Constant Type Value
CONSTANT_Class 7
CONSTANT_Fieldref 9
CONSTANT_Methodref 10
CONSTANT_InterfaceMethodref 11
CONSTANT_String 8
CONSTANT_Integer 3
CONSTANT_Float 4
CONSTANT_Long 5
CONSTANT_Double 6
CONSTANT_NameAndType 12
CONSTANT_Utf8 1
CONSTANT_MethodHandle 15
CONSTANT_MethodType 16
CONSTANT_InvokeDynamic 18

8-9 字节,表示常量池长度,00 23 (35) 表示常量池有 #1~#34项,注意 #0 项不计入,也没有值

0000000 ca fe ba be 00 00 00 34 00 23 0a 00 06 00 15 09

第#1项 0a 表示一个 Method 信息,00 06 和 00 15(21) 表示它引用了常量池中 #6 和 #21 项来获得这个方法的【所属类】和【方法名】

0000000 ca fe ba be 00 00 00 34 00 23 0a 00 06 00 15 09

第#2项 09 表示一个 Field 信息,00 16(22)和 00 17(23) 表示它引用了常量池中 #22 和 # 23 项来获得这个成员变量的【所属类】和【成员变量名】

0000000 ca fe ba be 00 00 00 34 00 23 0a 00 06 00 15 09

0000020 00 16 00 17 08 00 18 0a 00 19 00 1a 07 00 1b 07

第#3项 08 表示一个字符串常量名称,00 18(24)表示它引用了常量池中 #24 项

0000020 00 16 00 17 08 00 18 0a 00 19 00 1a 07 00 1b 07

第#4项 0a 表示一个 Method 信息,00 19(25) 和 00 1a(26) 表示它引用了常量池中 #25 和 #26项来获得这个方法的【所属类】和【方法名】

0000020 00 16 00 17 08 00 18 0a 00 19 00 1a 07 00 1b 07

第#5项 07 表示一个 Class 信息,00 1b(27) 表示它引用了常量池中 #27 项

0000020 00 16 00 17 08 00 18 0a 00 19 00 1a 07 00 1b 07

省略若干……

1.4 访问标识与继承信息

21 表示该 class 是一个类,公共的

0000660 29 56 00 21 00 05 00 06 00 00 00 00 00 02 00 01

05 表示根据常量池中 #5 找到本类全限定名

0000660 29 56 00 21 00 05 00 06 00 00 00 00 00 02 00 01

06 表示根据常量池中 #6 找到父类全限定名

0000660 29 56 00 21 00 05 00 06 00 00 00 00 00 02 00 01

表示接口的数量,本类为 0

0000660 29 56 00 21 00 05 00 06 00 00 00 00 00 02 00 01

1.5 Field 信息

表示成员变量数量,本类为 0

0000660 29 56 00 21 00 05 00 06 00 00 00 00 00 02 00 01

f.png
1.6 Method 信息

表示方法数量,本类为 2

0000660 29 56 00 21 00 05 00 06 00 00 00 00 00 02 00 01

一个方法由 访问修饰符,名称,参数描述,方法属性数量,方法属性组成

1.7 附加属性

  • 00 01 表示附加属性数量

  • 00 13 表示引用了常量池 #19 项,即【SourceFile】

  • 00 00 00 02 表示此属性的长度

  • 00 14 表示引用了常量池 #20 项,即【HelloWorld.java】

0001100 00 12 00 00 00 05 01 00 10 00 00 00 01 00 13 00

0001120 00 00 02 00 14

参考文献

docs.oracle.com/javase/spec…

2.字节码指令

2.1 入门

接着上一节,研究一下两组字节码指令,一个是

public cn.qinghong.jvm.t5.HelloWorld(); 构造方法的字节码指令

2a b7 00 01 b1
复制代码
  1. 2a => aload_0 加载 slot 0 的局部变量,即 this,做为下面的 invokespecial 构造方法调用的参数

  2. b7 => invokespecial 预备调用构造方法,哪个方法呢?

  3. 00 01 引用常量池中 #1 项,即【 Method java/lang/Object.””:()V 】

  4. b1 表示返回

另一个是public static void main(java.lang.String[]); 主方法的字节码指令

b2 00 02 12 03 b6 00 04 b1
复制代码
  1. b2 => getstatic 用来加载静态变量,哪个静态变量呢?

  2. 00 02 引用常量池中 #2 项,即【Field java/lang/System.out:Ljava/io/PrintStream;】

  3. 12 => ldc 加载参数,哪个参数呢?

  4. 03 引用常量池中 #3 项,即 【String hello world】

  5. b6 => invokevirtual 预备调用成员方法,哪个方法呢?

  6. 00 04 引用常量池中 #4 项,即【Method java/io/PrintStream.println:(Ljava/lang/String;)V】

  7. b1 表示返回

请参考

docs.oracle.com/javase/spec…

2.2 javap工具

自己分析类文件结构太麻烦了,Oracle 提供了 javap 工具来反编译 class 文件

[root@localhost ~]# javap -v HelloWorld.class 
Classfile /root/HelloWorld.class 
    Last modified Jul 7, 2019; size 597 bytes 
    MD5 checksum 361dca1c3f4ae38644a9cd5060ac6dbc 
Compiled from "HelloWorld.java" 
public class cn.itcast.jvm.t5.HelloWorld 
    minor version: 0 
    major version: 52 
    flags: ACC_PUBLIC, ACC_SUPER 
Constant pool: 
#1 = Methodref       #6.#21 // java/lang/Object."<init>":()V 
#2 = Fieldref        #22.#23      //java/lang/System.out:Ljava/io/PrintStream; 
#3 = String          #24   // hello world 
#4 = Methodref       #25.#26   // java/io/PrintStream.println: (Ljava/lang/String;)V 
#5 = Class          #27   // cn/itcast/jvm/t5/HelloWorld 
#6 = Class          #28    // java/lang/Object 
#7 = Utf8          <init> 
#8 = Utf8         ()V 
#9 = Utf8         Code 
#10 = Utf8        LineNumberTable 
#11 = Utf8        LocalVariableTable 
#12 = Utf8        this 
#13 = Utf8        Lcn/itcast/jvm/t5/HelloWorld;#14 = Utf8 main 
#15 = Utf8        ([Ljava/lang/String;)V 
#16 = Utf8       args 
#17 = Utf8       [Ljava/lang/String; 
#18 = Utf8       MethodParameters 
#19 = Utf8       SourceFile 
#20 = Utf8       HelloWorld.java 
#21 = NameAndType        #7:#8   // "<init>":()V 
#22 = Class        #29   // java/lang/System 
#23 = NameAndType        #30:#31  // out:Ljava/io/PrintStream; 
#24 = Utf8        hello world 
#25 = Class        #32 // java/io/PrintStream 
#26 = NameAndType        #33:#34 // println:(Ljava/lang/String;)V 
#27 = Utf8        cn/itcast/jvm/t5/HelloWorld 
#28 = Utf8        java/lang/Object 
#29 = Utf8        java/lang/System 
#30 = Utf8       out 
#31 = Utf8       Ljava/io/PrintStream; 
#32 = Utf8       java/io/PrintStream 
#33 = Utf8       println 
#34 = Utf8       (Ljava/lang/String;)V 
{ 
    public cn.itcast.jvm.t5.HelloWorld(); 
        descriptor: ()V 
        flags: ACC_PUBLIC 
        Code: 
            stack=1, locals=1, args_size=1 
            0: aload_0 
            1: invokespecial #1 // Method java/lang/Object." 
<init>":()V
            4: return 
        LineNumberTable: 
            line 4: 0 
        LocalVariableTable: 
            Start Length Slot Name Signature 
                0 5 0 this Lcn/itcast/jvm/t5/HelloWorld; 
    public static void main(java.lang.String[]); 
        descriptor: ([Ljava/lang/String;)V 
        flags: ACC_PUBLIC, ACC_STATIC 
        Code: 
            stack=2, locals=1, args_size=1 
        0: getstatic        #2  // Fieldjava/lang/System.out:Ljava/io/PrintStream; 
        3: ldc        #3    // String hello world 
        5: invokevirtual        #4   // Method java/io/PrintStream.println:(Ljava/lang/String;)V 
        8: return 
        LineNumberTable: 
            line 6: 0 
            line 7: 8 
        LocalVariableTable: 
            Start Length Slot Name Signature 
            0 9 0 args [Ljava/lang/String; 
    MethodParameters: 
        Name        Flags 
        args 
}
复制代码

2.3 图解方法执行流程

1)原始java代码

/**
* 演示 字节码指令 和 操作数栈、常量池的关系
*/
public class Demo3_1 {
public static void main(String[] args) {
    int a = 10;
    int b = Short.MAX_VALUE + 1;
    int c = a + b;
    System.out.println(c);
    }
}
复制代码

2)编译后的字节码文件

[root@localhost ~]# javap -v Demo3_1.class 
Classfile /root/Demo3_1.class 
    Last modified Jul 7, 2019; size 665 bytes 
    MD5 checksum a2c29a22421e218d4924d31e6990cfc5 
    Compiled from "Demo3_1.java" 
public class cn.itcast.jvm.t3.bytecode.Demo3_1 
    minor version: 0 
    major version: 52 
    flags: ACC_PUBLIC, ACC_SUPER 
Constant pool: 
 #1 = Methodref       #7.#26      // java/lang/Object."<init>":()V 
 #2 = Class           #27         // java/lang/Short 
 #3 = Integer         32768 
 #4 = Fieldref       #28.#29     //java/lang/System.out:Ljava/io/PrintStream; 
 #5 = Methodref      #30.#31     // java/io/PrintStream.println:(I)V 
 #6 = Class          #32 // cn/itcast/jvm/t3/bytecode/Demo3_1 
 #7 = Class          #33 // java/lang/Object 
 #8 = Utf8          <init> 
 #9 = Utf8          ()V 
 #10 = Utf8          Code 
 #11 = Utf8          LineNumberTable 
 #12 = Utf8          LocalVariableTable 
 #13 = Utf8          this 
 #14 = Utf8          Lcn/itcast/jvm/t3/bytecode/Demo3_1; 
 #15 = Utf8          main 
 #16 = Utf8          ([Ljava/lang/String;)V 
 #17 = Utf8          args 
 #18 = Utf8          [Ljava/lang/String; 
 #19 = Utf8          a#20 = Utf8 I 
 #20 = Utf8          HelloWorld.java
 #21 = Utf8          b 
 #22 = Utf8          c 
 #23 = Utf8          MethodParameters 
 #24 = Utf8          SourceFile 
 #25 = Utf8          Demo3_1.java 
 #26 = NameAndType   #8:#9     // "<init>":()V 
 #27 = Utf8          java/lang/Short 
 #28 = Class          #34     // java/lang/System 
 #29 = NameAndType    #35:#36     // out:Ljava/io/PrintStream; 
 #30 = Class          #37     // java/io/PrintStream 
 #31 = NameAndType    #38:#39     // println:(I)V 
 #32 = Utf8          cn/itcast/jvm/t3/bytecode/Demo3_1 
 #33 = Utf8          java/lang/Object 
 #34 = Utf8          java/lang/System 
 #35 = Utf8          out 
 #36 = Utf8          Ljava/io/PrintStream; 
 #37 = Utf8          java/io/PrintStream 
 #38 = Utf8          println 
 #39 = Utf8          (I)V 
{ 
    public cn.itcast.jvm.t3.bytecode.Demo3_1(); 
        descriptor: ()V 
        flags: ACC_PUBLIC 
        Code: 
        stack=1, locals=1, args_size=1 
        0: aload_0 
        1: invokespecial #1          // Method java/lang/Object." 
        <init>":()V
        4: return 
        LineNumberTable: 
        line 6: 0 
        LocalVariableTable: 
        Start  Length Slot Name Signature 
        0        5     0   this Lcn/itcast/jvm/t3/bytecode/Demo3_1; 
    public static void main(java.lang.String[]); 
    descriptor: ([Ljava/lang/String;)V 
    flags: ACC_PUBLIC, ACC_STATIC 
    Code:
    stack=2, locals=4, args_size=1 
    0: bipush 10 
    2: istore_1
    3: ldc        #3        // int 32768 
    5: istore_2 
    6: iload_1 
    7: iload_2 
    8: iadd 
    9: istore_3 
    10: getstatic   #4      // Field 
    java/lang/System.out:Ljava/io/PrintStream; 
    13: iload_3 
    14: invokevirtual   #5     // Method 
    java/io/PrintStream.println:(I)V 
    17: return 
    LineNumberTable: 
    line 8: 0 
    line 9: 3
    (stack=2,locals=4) 
    line 10: 6 
    line 11: 10 
    line 12: 17 
    LocalVariableTable: 
        Start Length Slot Name Signature 
          0    18     0   args  [Ljava/lang/String; 
          3    15     1    a    I 
          6    12     2    b   I 
          10    8     3    c   I 
        MethodParameters: 
            Name         Flags 
           args 
}
复制代码

3) 常量池载入运行时常量池

b.png

4)方法字节码载入方法区

c.png

5) main 线程开始运行,分配栈帧内存

(stack=2,locals=4)

d.png

6)执行引擎开始执行字节码

bipush 10

  • 将一个 byte 压入操作数栈(其长度会补齐 4 个字节),类似的指令还有
  • sipush 将一个 short 压入操作数栈(其长度会补齐 4 个字节)
  • ldc 将一个 int 压入操作数栈
  • ldc2_w 将一个 long 压入操作数栈(分两次压入,因为 long 是 8 个字节)
  • 这里小的数字都是和字节码指令存在一起,超过 short 范围的数字存入了常量池

e.png

istore_1

  • 将操作数栈顶数据弹出,存入局部变量表的 slot 1

g.png

ldc #3

  • 从常量池加载 #3 数据到操作数栈
  • 注意 Short.MAX_VALUE 是 32767,所以 32768 = Short.MAX_VALUE +1 实际是在编译期间计算好的

h.png
istore_2

i.png
iload_1

j.png
iload_2

k.png
iadd

l.png
istore_3

m.png
getstatic #4

你.png

n2.png
iload_3

o.png
invokevirtual #5

  • 找到常量池 #5 项
  • 定位到方法区 java/io/PrintStream.println:(I)V 方法
  • 生成新的栈帧(分配 locals、stack等)
  • 传递参数,执行新栈帧中的字节码

p.png

  • 执行完毕,弹出栈帧
  • 清除 main 操作数栈内容

q.png
return

  • 完成 main 方法调用,弹出 main 栈帧
  • 程序结束

2.4 练习分析i++

目的:从字节码角度分析 a++ 相关题目

源码:

/**
 * 从字节码角度分析 a++  相关题目
 */
public class Demo3_2 {
    public static void main(String[] args) {
        int a = 10;
        int b = a++ + ++a + a--;
        System.out.println(a);
        System.out.println(b);
    }
}
复制代码

字节码

public static void main(java.lang.String[]); 
    descriptor: ([Ljava/lang/String;)V 
        flags: (0x0009) ACC_PUBLIC, ACC_STATIC 
        Code: 
            stack=2, locals=3, args_size=1 
                0: bipush      10 
                2: istore_1 
                3: iload_1 
                4: iinc      1, 1 
                7: iinc      1, 1 
                10: iload_1 
                11: iadd 
                12: iload_1 
                13: iinc      1, -1 
                16: iadd 
                17: istore_218: getstatic      #2      // Fieldjava/lang/System.out:Ljava/io/PrintStream; 
                21: iload_1 
                22: invokevirtual      #3      // Method java/io/PrintStream.println:(I)V 
                25: getstatic      #2      // Field java/lang/System.out:Ljava/io/PrintStream; 
                28: iload_2 
                29: invokevirtual      #3      // Methodjava/io/PrintStream.println:(I)V 
                32: return 
            LineNumberTable: 
                line 8: 0 
                line 9: 3 
                line 10: 18 
                line 11: 25 
                line 12: 32 
            LocalVariableTable: 
                Start Length Slot Name Signature 
                  0    33     0   args  [Ljava/lang/String; 
                  3    30     1    a    I 
                  18   15     2    b    I
复制代码

分析:

  • 注意 iinc 指令是直接在局部变量 slot 上进行运算
  • a++ 和 ++a 的区别是先执行 iload 还是 先执行 iinc

r.png

r1.png

r2.png

r3.png

r4.png

r5.png

2.5 条件判断指令指令

biao.png

几点说明:

  • byte,short,char 都会按 int 比较,因为操作数栈都是 4 字节
  • goto 用来进行跳转到指定行号的字节码

源码:

public class Demo3_3 {
    public static void main(String[] args) {
        int a = 0;
        if(a == 0) {
            a = 10;
        } else {
            a = 20;
        }
    }
}
复制代码

字节码:

0: iconst_0
1: istore_1
2: iload_1
3: ifne          12
6: bipush        10
8: istore_1
9: goto          15
12: bipush       20
14: istore_1
15: return
复制代码

思考 :细心的同学应当注意到,以上比较指令中没有 long,flfloat,double 的比较,那么它们要比较怎么办?参考 docs.oracle.com/javase/spec…

2.6 循环控制指令

其实循环控制还是前面介绍的那些指令,例如 while 循环:

public class Demo3_4 {
    public static void main(String[] args) {
        int a = 0;
        while (a < 10) {
            a++;
        }
    }
}
复制代码

字节码

0: iconst_0
1: istore_1
2: iload_1
3: bipush        10
5: if_icmpge     14
8: iinc          1, 1
11: goto         2
14: return
复制代码

再比如 do while 循环:

public class Demo3_5 {
    public static void main(String[] args) {
        int a = 0;
        do {
            a++;
        } while (a < 10);
    }
}

复制代码

字节码是:

 0: iconst_0
 1: istore_1
 2: iinc        1, 1
 5: iload_1
 6: bipush      10
 8: if_icmplt    2
11: return
复制代码

最后再看看 for 循环:

public class Demo3_6 {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
        }
    }
}
复制代码

字节码是:

0: iconst_0 
1: istore_1 
2: iload_1 
3: bipush           10 
5: if_icmpge        14 
8: iinc            1, 1 
11: goto            2 
14: return 
复制代码

注意比较 while 和 for 的字节码,你发现它们是一模一样的,殊途也能同归?

2.7 练习判断结果

请从字节码角度分析,下列代码运行的结果:

public class Demo3_6_1 {
    public static void main(String[] args) {
        int i = 0;
        int x = 0;
        while (i < 10) {
            x = x++;
            i++;
        }
        System.out.println(x);
    }
}
复制代码

2.8 构造方法

1) < cinit >()V
public class Demo3_8_1 {

    static {
        i = 20;
    }

    static {
        i = 30;
    }

    static int i = 10;

    public static void main(String[] args) {
        System.out.println(Demo3_8_1.i);
    }
}

复制代码

编译器会按从上至下的顺序,收集所有 static 静态代码块和静态成员赋值的代码,合并为一个特殊的方法 <cinit>()V :

0: bipush        10
2: putstatic     #2    // Field i:I
5: bipush        20
7: putstatic     #2    // Field i:I
10: bipush       30
12: putstatic    #2    // Field i:I
15: return
复制代码

<cinit>()V 方法会在类加载的初始化阶段被调用

练习可以自己调整一下 static 变量和静态代码块的位置,观察字节码的改动

2)<init>()V
public class Demo3_8_2 {


    private String a = "s1";

    {
        b = 20;
    }

    private int b = 10;

    {
        a = "s2";
    }

    public Demo3_8_2(String a, int b) {
        this.a = a;
        this.b = b;
    }

    public static void main(String[] args) {
        Demo3_8_2 d = new Demo3_8_2("s3", 30);
        System.out.println(d.a);
        System.out.println(d.b);
    }
}

复制代码

编译器会按从上至下的顺序,收集所有 {} 代码块和成员变量赋值的代码,形成新的构造方法,但原始构造方法内的代码总是在最后

public cn.itcast.jvm.t3.bytecode.Demo3_8_2(java.lang.String, int);
    descriptor: (Ljava/lang/String;I)V
    flags: ACC_PUBLIC
    Code:
        stack=2, locals=3, args_size=3
            0: aload_0
            1: invokespecial  #1     // super.<init>()V
            4: aload_0
            5: ldc            #2     // <- "s1"
            7: putfield       #3     // -> this.a
            10: aload_0
            11: bipush        20     // <- 20
            13: putfield      #4     // -> this.b
            16: aload_0
            17: bipush        10     // <- 10
            19: putfield      #4     // -> this.b
            22: aload_0
            23: ldc           #5     //<- "s2"
            25: putfield      #3     // -> this.a
            28: aload_0              // ------------------------------
            29: aload_1              // <- slot 1(a) "s3"            |
            30: putfield      #3     // -> this.a                    |
            33: aload_0                                              |
            34: iload_2              // <- slot 2(b) 30              |
            35: putfield      #4     // -> this.b -------------------
            38: return
            LineNumberTable: ...
            LocalVariableTable:
                Start Length Slot Name Signature
                0     39     0   this   Lcn/itcast/jvm/t3/bytecode/Demo3_8_2;
                0     39     1    a     Ljava/lang/String;
                0     39     2    b     I
        MethodParameters: ...
复制代码

2.9 方法调用

看一下几种不同的方法调用对应的字节码指令


public class Demo3_9 {
    public Demo3_9() { }

    private void test1() { }

    private final void test2() { }

    public void test3() { }

    public static void test4() { }

    @Override
    public String toString() {
        return super.toString();
    }

    public static void main(String[] args) {
        Demo3_9 d = new Demo3_9();
        d.test1();
        d.test2();
        d.test3();
        d.test4();
        Demo3_9.test4();
        d.toString();
    }

}

复制代码

*字节码:

0: new              #2   // class cn/itcast/jvm/t3/bytecode/Demo3_9
3: dup
4: invokespecial    #3   // Method "<init>":()V
7: astore_1
8: aload_1
9: invokespecial    #4   // Method test1:()V
12: aload_1
13: invokespecial   #5   // Method test2:()V
16: aload_1
17: invokevirtual   #6   // Method test3:()V
20: aload_1
21: pop
22: invokestatic    #7   // Method test4:()V
25: invokestatic    #7   // Method test4:()V
28: return
复制代码
  • new 是创建【对象】,给对象分配堆内存,执行成功会将【对象引用】压入操作数栈
  • dup 是赋值操作数栈栈顶的内容,本例即为【对象引用】,为什么需要两份引用呢,一个是要配合 invokespecial 调用该对象的构造方法 “”:()V (会消耗掉栈顶一个引用),另一个要配合 astore_1 赋值给局部变量
  • 最终方法(fifinal),私有方法(private),构造方法都是由 invokespecial 指令来调用,属于静态绑定
  • 普通成员方法是由 invokevirtual 调用,属于动态绑定,即支持多态
  • 成员方法与静态方法调用的另一个区别是,执行方法前是否需要【对象引用】
  • 比较有意思的是 d.test4(); 是通过【对象引用】调用一个静态方法,可以看到在调用invokestatic 之前执行了 pop 指令,把【对象引用】从操作数栈弹掉了?
  • 还有一个执行 invokespecial 的情况是通过 super 调用父类方法

2.10 多态的原理

/**
 * 演示多态原理,注意加上下面的 JVM 参数,禁用指针压缩
 * -XX:-UseCompressedOops -XX:-UseCompressedClassPointers
 */
public class Demo3_10 {

    public static void test(Animal animal) {
        animal.eat();
        System.out.println(animal.toString());
    }

    public static void main(String[] args) throws IOException {
        test(new Cat());
        test(new Dog());
        System.in.read();
    }
}

abstract class Animal {
    public abstract void eat();

    @Override
    public String toString() {
        return "我是" + this.getClass().getSimpleName();
    }
}

class Dog extends Animal {

    @Override
    public void eat() {
        System.out.println("啃骨头");
    }
}

class Cat extends Animal {

    @Override
    public void eat() {
        System.out.println("吃鱼");
    }
}

复制代码

1 运行代码
停在 System.in.read() 方法上,这时运行 jps 获取进程 id
2 运行 HSDB 工具
进入 JDK 安装目录,执行

java -cp ./lib/sa-jdi.jar sun.jvm.hotspot.HSDB
复制代码

进入图形界面 attach 进程 id

3 查找某个对象

打开 Tools -> Find Object By Query

输入 select d from cn.itcast.jvm.t3.bytecode.Dog d 点击 Execute 执行

d1.png
4 查看对象内存结构

点击超链接可以看到对象的内存结构,此对象没有任何属性,因此只有对象头的 16 字节,前 8 字节是MarkWord,后 8 字节就是对象的 Class 指针
但目前看不到它的实际地址

d2.png
5 查看对象Class的内存地址

可以通过 Windows -> Console 进入命令行模式,执行

mem 0x00000001299b4978 2
复制代码

mem 有两个参数,参数 1 是对象地址,参数 2 是查看 2 行(即 16 字节)

结果中第二行 0x000000001b7d4028 即为 Class 的内存地址

d3.png

6 查看类的vtable

  • 方法1:Alt+R 进入 Inspector 工具,输入刚才的 Class 内存地址,看到如下界面

  • 方法2:或者 Tools -> Class Browser 输入 Dog 查找,可以得到相同的结果

无论通过哪种方法,都可以找到 Dog Class 的 vtable 长度为 6,意思就是 Dog 类有 6 个虚方法(多态相关的,fifinal,static 不会列入)

那么这 6 个方法都是谁呢?从 Class 的起始地址开始算,偏移 0x1b8 就是 vtable 的起始地址,进行计

算得到:

0x000000001b7d4028 
                1b8 + 
\--------------------- 
0x000000001b7d41e0
复制代码

通过 Windows -> Console 进入命令行模式,执行

mem 0x000000001b7d41e0 6

0x000000001b7d41e0: 0x000000001b3d1b10
0x000000001b7d41e8: 0x000000001b3d15e8
0x000000001b7d41f0: 0x000000001b7d35e8
0x000000001b7d41f8: 0x000000001b3d1540
0x000000001b7d4200: 0x000000001b3d1678
0x000000001b7d4208: 0x000000001b7d3fa8````
复制代码

就得到了 6 个虚方法的入口地址

7 验证方法地址

通过 Tools -> Class Browser 查看每个类的方法定义,比较可知

Dog - public void eat() @0x000000001b7d3fa8
Animal - public java.lang.String toString() @0x000000001b7d35e8;
Object - protected void finalize() @0x000000001b3d1b10;
Object - public boolean equals(java.lang.Object) @0x000000001b3d15e8;
Object - public native int hashCode() @0x000000001b3d1540;
Object - protected native java.lang.Object clone() @0x000000001b3d1678;
复制代码

对号入座,发现

  • eat() 方法是 Dog 类自己的

  • toString() 方法是继承 String 类的

  • fifinalize() ,equals(),hashCode(),clone() 都是继承 Object 类的

8 小结

当执行 invokevirtual 指令时,

  1. 先通过栈帧中的对象引用找到对象

  2. 分析对象头,找到对象的实际 Class

  3. Class 结构中有 vtable,它在类加载的链接阶段就已经根据方法的重写规则生成好了

  4. 查表得到方法的具体地址

  5. 执行方法的字节码

2.11 异常处理

try-catch

public class Demo3_11_1 {

    public static void main(String[] args) {
        int i = 0;
        try {
            i = 10;
        } catch (Exception e) {
            i = 20;
        }
    }
}
复制代码

注意为了抓住重点,下面的字节码省略了不重要的部分

public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
        stack=1, locals=3, args_size=1
            0: iconst_0
            1: istore_1
            2: bipush      10
            4: istore_1
            5: goto        12
            8: astore_2
            9: bipush      20
            11: istore_1
            12: return
        Exception table:
            from to target type
            2    5    8    Class java/lang/Exception
        LineNumberTable: ...
        LocalVariableTable:
            Start Length Slot Name Signature
             9     3     2    e     Ljava/lang/Exception;
             0     13    0    args  [Ljava/lang/String;
             2     11    1    i     I
        StackMapTable: ...
    MethodParameters: ...
}
复制代码
  • 可以看到多出来一个 Exception table 的结构,[from, to) 是前闭后开的检测范围,一旦这个范围内的字节码执行出现异常,则通过 type 匹配异常类型,如果一致,进入 target 所指示行号
  • 8 行的字节码指令 astore_2 是将异常对象引用存入局部变量表的 slot 2 位置

多个single-catch块的情况

public class Demo3_11_2 {
    public static void main(String[] args) {
        int i = 0;
        try {
            i = 10;
        } catch (ArithmeticException e) {
            i = 30;
        } catch (NullPointerException e) {
            i = 40;
        } catch (Exception e) {
            i = 50;
        }
    }
}
复制代码
public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
        stack=1, locals=3, args_size=1
            0: iconst_0
            1: istore_1
            2: bipush       10
            4: istore_1
            5: goto         26
            8: astore_2
            9: bipush       30
            11: istore_1
            12: goto        26
            15: astore_2
            16: bipush      40
            18: istore_1
            19: goto        26
            22: astore_2
            23: bipush      50
            25: istore_1
            26: return
    Exception table:
        from to target type
           2  5   8     Class java/lang/ArithmeticException
           2  5  15    Class java/lang/NullPointerException
           2  5  22    Class java/lang/Exception
    LineNumberTable: ...
    LocalVariableTable:
        Start Length Slot Name Signature
          9    3      2    e     Ljava/lang/ArithmeticException;
          16   3      2    e     Ljava/lang/NullPointerException;
          23   3      2    e     Ljava/lang/Exception;
          0    27     0    args    [Ljava/lang/String;
          2    25     1    i      I
        StackMapTable: ...
    MethodParameters: ..
复制代码
  • 因为异常出现时,只能进入 Exception table 中一个分支,所以局部变量表 slot 2 位置被共用

multi-catch的情况


public class Demo3_11_3 {
    public static void main(String[] args) {
        try {
            Method test = Demo3_11_3.class.getMethod("test");
            test.invoke(null);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public static void test() {
        System.out.println("ok");
    }
}

复制代码
public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
        stack=3, locals=2, args_size=1
            0: ldc          #2
            2: ldc          #3
            4: iconst_0
            5: anewarray    #4
            8: invokevirtual #5
            11: astore_1
            12: aload_1
            13: aconst_null
            14: iconst_0
            15: anewarray    #6
            18: invokevirtual #7
            21: pop
            22: goto        30
            25: astore_1
            26: aload_1
            27: invokevirtual #11   // e.printStackTrace:()V
            30: return
    Exception table:
    from to target type
      0   22   25   Class java/lang/NoSuchMethodException
      0   22   25   Class java/lang/IllegalAccessException
      0   22   25   Class java/lang/reflect/InvocationTargetException
    LineNumberTable: ...
    LocalVariableTable:
        Start Length Slot Name Signature
         12   10     1    test    Ljava/lang/reflect/Method;
         26   4      1    e       Ljava/lang/ReflectiveOperationException;
         0    31     0    args    [Ljava/lang/String;
        StackMapTable: ...
    MethodParameters: ...
复制代码

finally

public class Demo3_11_4 {

    public static void main(String[] args) {
        int i = 0;
        try {
            i = 10;
        } catch (Exception e) {
            i = 20;
        } finally {
            i = 30;
        }
    }
}

复制代码
public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
        stack=1, locals=4, args_size=1
            0: iconst_0
            1: istore_1     // 0 -> i
            2: bipush   10  // try --------------------------------------
            4: istore_1     // 10 -> i 
            5: bipush   30  // finally 
            7: istore_1     // 30 -> i 
            8: goto     27  // return -----------------------------------
            11: astore_2    // catch Exceptin -> e ----------------------
            12: bipush  20  // |
            14: istore_1    // 20 -> i 
            15: bipush  30  // finally 
            17: istore_1    // 30 -> i 
            18: goto    27  // return -----------------------------------
            21: astore_3    // catch any -> slot 3 ----------------------
            22: bipush  30  // finally |
            24: istore_1    // 30 -> i 
            25: aload_3     // <- slot 3 
            26: athrow      // throw ------------------------------------
            27: return
        Exception table:
            from to target type
             2 5 11 Class java/lang/Exception
             2 5 21 any // 剩余的异常类型,比如 Error
             11 15 21 any // 剩余的异常类型,比如 Error
        LineNumberTable: ...
        LocalVariableTable:
            Start Length Slot Name Signature
               12 3 2 e Ljava/lang/Exception;
               0 28 0 args [Ljava/lang/String;
               2 26 1 i I
        StackMapTable: ...
    MethodParameters: ...
复制代码

可以看到 fifinally 中的代码被复制了 3 份,分别放入 try 流程,catch 流程以及 catch 剩余的异常类型流程

2.12 练习- fifinally面试题

fifinally出现了return

先问问自己,下面的题目输出什么?

public class Demo3_12_2 {
    public static void main(String[] args) {
        int result = test();
        System.out.println(result);
    }

    public static int test() {
        int i = 10;
        try {
            return i;
        } finally {
            i = 20;
        }
    }
}

复制代码
  • 由于 fifinally 中的 ireturn 被插入了所有可能的流程,因此返回结果肯定以 fifinally 的为准
  • 至于字节码中第 2 行,似乎没啥用,且留个伏笔,看下个例子
  • 跟上例中的 fifinally 相比,发现没有 athrow 了,这告诉我们:如果在 fifinally 中出现了 return,会吞掉异常???,可以试一下下面的代码
public class Demo3_12_1 {
    public static void main(String[] args) {
        int result = test();
        System.out.println(result);
    }

    public static int test() {
        try {
            int i = 1/0;
            return 10;
        } finally {
            return 20;
        }
    }
}
复制代码

fifinally对返回值影响

同样问问自己,下面的题目输出什么?

public class Demo3_12_2 {
    public static void main(String[] args) {
        int result = test();
        System.out.println(result);
    }

    public static int test() {
        int i = 10;
        try {
            return i;
        } finally {
            i = 20;
        }
    }
}

复制代码
public static int test();
descriptor: ()I

flags: ACC_PUBLIC, ACC_STATIC

Code:

stack=1, locals=3, args_size=0

0: bipush 10 // <- 10 放入栈顶

2: istore_0 // 10 -> i

3: iload_0 // <- i(10)

4: istore_1 // 10 -> slot 1,暂存至 slot 1,目的是为了固定返回值

5: bipush 20 // <- 20 放入栈顶

7: istore_0 // 20 -> i

8: iload_1 // <- slot 1(10) 载入 slot 1 暂存的值

9: ireturn // 返回栈顶的 int(10)

10: astore_2

11: bipush 20

13: istore_0

14: aload_2

15: athrow

Exception table:

from to target type

3 5 10 any

LineNumberTable: ...

LocalVariableTable:

Start Length Slot Name Signature

3 13 0 i I

注意

StackMapTable: ...
复制代码

2.13 synchronized

public class Demo3_13 {

    public static void main(String[] args) {
        Object lock = new Object();
        synchronized (lock) {
            System.out.println("ok");
        }
    }
}

复制代码
public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
        stack=2, locals=4, args_size=1
            0: new #2            // new Object
            3: dup
            4: invokespecial #1  // invokespecial <init>:()V
            7: astore_1          // lock引用 -> lock
            8: aload_1           // <- lock (synchronized开始)
            9: dup
            10: astore_2         // lock引用 -> slot 2
            11: monitorenter     // monitorenter(lock引用)
            12: getstatic   #3   // <- System.out
            15: ldc         #4   // <- "ok"
            17: invokevirtual #5 // invokevirtual println:(Ljava/lang/String;)V
            20: aload_2          // <- slot 2(lock引用)
            21: monitorexit      // monitorexit(lock引用)
            22: goto 30
            25: astore_3         // any -> slot 3
            26: aload_2          // <- slot 2(lock引用)
            27: monitorexit      // monitorexit(lock引用)
            28: aload_3
            29: athrow
            30: return
        Exception table:
            from to target type
              12 22 25 any
              25 28 25 any
             LineNumberTable: ...
        LocalVariableTable:
            Start Length Slot Name Signature
                0 31 0 args [Ljava/lang/String;
                8 23 1 lock Ljava/lang/Object;
        StackMapTable: ...
    MethodParameters: ...
复制代码

注意 方法级别的 synchronized 不会在字节码指令中有所体现

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享