使用javap -c classname
您可以自己检查字节码,
这是选项1:
(注意,我必须初始化,a = null
否则无法编译)
7: aconst_null
8: astore_2
9: iload_1
10: tableswitch{ //1 to 3
1: 36;
2: 42;
3: 48;
default: 51 }
36: ldc #3; //String Cueck
38: astore_2
39: goto 51
42: ldc #4; //String Blub
44: astore_2
45: goto 51
48: ldc #5; //String Writing cases is BORING!
50: astore_2
51: getstatic #6; //Field java/lang/System.out:Ljava/io/PrintStream;
54: aload_2
55: invokevirtual #7; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
58: return
这是选项2:
7: iload_1
8: tableswitch{ //1 to 3
1: 36;
2: 47;
3: 58;
default: 66 }
36: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
39: ldc #4; //String Cueck
41: invokevirtual #5; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
44: goto 66
47: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
50: ldc #6; //String Blub
52: invokevirtual #5; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
55: goto 66
58: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
61: ldc #7; //String Writing cases is BORING!
63: invokevirtual #5; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
66: return
就个人而言,我认为在这种情况下没有更好的字节码,我发现选项 1 更具可读性。