本帖最后由 Synaric 于 2015-9-26 23:14 编辑
今天被这个问题卡住了,不多说上代码
- public class MultipleSelectionsDemo {
- public static void main(String[] args) {
- String str = "A";
-
- switch (str) {
- case "A":
- System.out.println("case A");
- break;
- case "B":
- System.out.println("case B");
- break;
- case "C":
- System.out.println("case C");
- break;
- default:
- break;
- }
- }
- }
复制代码 反编译下
- import java.io.PrintStream;
- public class MultipleSelectionsDemo
- {
- public MultipleSelectionsDemo()
- {
- }
- public static void main(String args[])
- {
- String str = "A";
- String s;
- switch((s = str).hashCode())
- {
- default:
- break;
- case 65: // 'A'
- if(s.equals("A"))
- System.out.println("case A");
- break;
- case 66: // 'B'
- if(s.equals("B"))
- System.out.println("case B");
- break;
- case 67: // 'C'
- if(s.equals("C"))
- System.out.println("case C");
- break;
- }
- }
- }
复制代码
可以看到编译器偷偷加了点什么,case后面依旧只能跟常量,通过String.hashCode和String.equals来控制流程。
继续用javap看看switch实现
- Code:
- 0: ldc #16 // String A
- 2: astore_1
- 3: aload_1
- 4: dup
- 5: astore_2
- 6: invokevirtual #18 // Method java/lang/String.hashCode:()I
- 9: lookupswitch { // 3
- 65: 44
- 66: 56
- 67: 68
- default: 113
- }
- 44: aload_2
- 45: ldc #16 // String A
- 47: invokevirtual #24 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
- 50: ifne 80
- 53: goto 113
- 56: aload_2
- 57: ldc #28 // String B
- 59: invokevirtual #24 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
- 62: ifne 91
- 65: goto 113
- 68: aload_2
- 69: ldc #30 // String C
- 71: invokevirtual #24 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
- 74: ifne 102
- 77: goto 113
- 80: getstatic #32 // Field java/lang/System.out:Ljava/io/PrintStream;
- 83: ldc #38 // String case A
- 85: invokevirtual #40 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
- 88: goto 113
- 91: getstatic #32 // Field java/lang/System.out:Ljava/io/PrintStream;
- 94: ldc #46 // String case B
- 96: invokevirtual #40 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
- 99: goto 113
- 102: getstatic #32 // Field java/lang/System.out:Ljava/io/PrintStream;
- 105: ldc #48 // String case C
- 107: invokevirtual #40 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
- 110: goto 113
- 113: return
- }
复制代码 好吧看来是lookupswitch了,新世界的大门打开了,TM真是没完没了(/゚Д゚)/ 以后深入研究JVM下。。
|
|