Switch Java 问题:大小写表达式必须是常量表达式

2022-09-01 16:35:42

我在开关/案例声明中遇到了问题。错误显示:“大小写表达式必须是常量表达式”。我理解这个错误,我可以使用If来解决它,但有人可以告诉我为什么case表达式在开关/case中必须是常量的。我的错误的代码示例:

public boolean onOptionsItemSelected(MenuItem item) {
    int idDirectory = ((MenuItem) findViewById(R.id.createDirectory)).getItemId();
    int idSuppression = ((MenuItem) findViewById(R.id.recycleTrash)).getItemId();
    int idSeeTrash = ((MenuItem) findViewById(R.id.seeTrash)).getItemId();

    switch (item.getItemId()) {
    case idDirectory:
        createDirectory(currentDirectory);
        break;
    case idSuppression:
        recycleTrash();
        break;
    case idSeeTrash:
        seeTrash();
        break;
    }

    return super.onOptionsItemSelected(item);
}

谢谢你的解释!


答案 1

因此,可以在编译阶段对其进行评估(静态检查)

请参见:http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.11,了解 .switch

此外,它可以帮助您更好地理解如何将其转换为字节码:switch

class Switch {
  void x(int n ) {
    switch( n ) {
      case 1: System.out.println("one"); break;
      case 9: System.out.println("nine"); break;
      default:  System.out.println("nothing"); break;
    }
  }
}

编译后:

C:\>javap -c Switch
Compiled from "Switch.java"
class Switch extends java.lang.Object{
Switch();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

void x(int);
  Code:
   0:   iload_1
   1:   lookupswitch{ //2
                1: 28;
                9: 39;
                default: 50 }
   28:  getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   31:  ldc     #3; //String one
   33:  invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   36:  goto    58
   39:  getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   42:  ldc     #5; //String nine
   44:  invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   47:  goto    58
   50:  getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   53:  ldc     #6; //String nothing
   55:  invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   58:  return

}

查看标记为1:

 1:   lookupswitch{ //2
            1: 28;
            9: 39;
            default: 50 }

它评估该值并转到其他行。例如,如果值为值,它将跳转到指令39:9

   39:  getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;
   42:  ldc     #5; //String nine
   44:  invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   47:  goto    58

这反过来又跳到指令58:

   58:  return

如果对其进行动态评估,所有这些都是不可能的。这就是原因。


答案 2

在eclipse IDE中很简单,在切换句子CTRL + 1和转换开关句子 - if-else句子 http://tools.android.com/tips/non-constant-fields