深入JVM字节码探索switch枚举
本文主要讨论对枚举switch
的实现原理。
以下代码作为示例:
enum Foobar {
FOO,
BAR;
}
class Test {
static int test(Foobar var0) {
switch (var0) {
case FOO:
return 1;
case BAR:
return 2;
default:
return 0;
}
}
}
编译后的字节码:
Compiled from "Test.java"
class Test {
Test();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
static int test(Foobar);
Code:
0: getstatic #2 // Field Test$1.$SwitchMap$Foobar:[I
3: aload_0
4: invokevirtual #3 // Method Foobar.ordinal:()I
7: iaload
8: lookupswitch {
// 2
1: 36
2: 38
default: 40
}
36: iconst_1
37: ireturn
38: iconst_2
39: ireturn
40: iconst_0
41: ireturn
}
Compiled from "Test.java"
class Test$1 {
static final int[] $SwitchMap$Foobar;
static {
};
Code:
0: invokestatic #1 // Method Foobar.values:()[LFoobar;
3: arraylength
4: newarray int
6: putstatic #2 // Field $SwitchMap$Foobar:[I
9: getstatic #2 // Field $SwitchMap$Foobar:[I
12: getstatic #3 // Field Foobar.FOO:LFoobar;
15: invokevirtual #4 // Method Foobar.ordinal:()I
18: iconst_1
19: iastore
20