Java 7 String switch 反编译:意外指令
我反编译了一个非常简单的类,它使用新的 Java 7 String Switch 功能。
类:
public class StringSwitch {
public static void main(String[] args) {
final String color = "red";
switch (color) {
case "red":
System.out.println("IS RED!");
break;
case "black":
System.out.println("IS BLACK");
break;
case "blue":
System.out.println("IS BLUE");
break;
case "green":
System.out.println("IS GREEN");
break;
}
}
}
针对此类运行 Java 7“javap”,生成一组有趣的指令(完整的反汇编代码可在 这里):
public static void main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=4, args_size=1
...
12: lookupswitch { // 4
112785: 56
3027034: 84
93818879: 70
98619139: 98
default: 109
}
56: aload_2
57: ldc #2 // String red
...
110: tableswitch { // 0 to 3
0: 140
1: 151
2: 162
3: 173
default: 181
}
140: getstatic #8 // Field java/lang/System.out:Ljava/io/PrintStream;
143: ldc #9 // String IS RED!
...
181: return
“LOOKUPSWITCH”是switch case稀疏时使用的指令,可以替代TABLESWITCH,即“switch”语句的默认指令。
那么,问题是,为什么我们会看到“LOOKUPSWITCH”后面跟着“TABLESWITCH”?
谢谢 卢西亚诺
I have decompiled a very simple class that uses the new Java 7 String Switch feature.
The class:
public class StringSwitch {
public static void main(String[] args) {
final String color = "red";
switch (color) {
case "red":
System.out.println("IS RED!");
break;
case "black":
System.out.println("IS BLACK");
break;
case "blue":
System.out.println("IS BLUE");
break;
case "green":
System.out.println("IS GREEN");
break;
}
}
}
Running the Java 7 "javap" against this class, generates an interesting set of instructions (the complete disassembled code is available here):
public static void main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=4, args_size=1
...
12: lookupswitch { // 4
112785: 56
3027034: 84
93818879: 70
98619139: 98
default: 109
}
56: aload_2
57: ldc #2 // String red
...
110: tableswitch { // 0 to 3
0: 140
1: 151
2: 162
3: 173
default: 181
}
140: getstatic #8 // Field java/lang/System.out:Ljava/io/PrintStream;
143: ldc #9 // String IS RED!
...
181: return
The "LOOKUPSWITCH" is an instruction used when the switch case is sparse and can replace the TABLESWITCH, that is the default instruction for "switch" statements.
So, the question is, why are we seeing a "LOOKUPSWITCH" followed by a "TABLESWITCH"?
Thanks
Luciano
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 switch 中的字符串查找正确的 case 语句需要两步过程。
另请注意,指定您使用的编译器很有用 - javac 或 ECJ(Java 的 Eclipse 编译器)。两种编译器生成的字节码可能不同。
With strings in switch finding the correct case statement is a 2 step process.
Also note that it is useful to specify which compiler you used - javac or ECJ (Eclipse compiler for java). Both compilers may generate the bytecode differently.