在开关情况下枚举引用 [英] enum referencing in switch case

查看:113
本文介绍了在开关情况下枚举引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

枚举颜色{RED,GREEN,BLUE};

  
class SwitchEnum
{
public static void main(String [] args)
{
颜色c = Color.GREEN;
switch(c)
{
case RED:
System.out.println(red);
break;
case GREEN:
System.out.println(green);
break;
case BLUE:
System.out.println(blue);
break;
}
}
}

上面的代码编译好,我的问题是为什么在创建颜色引用c时,我们需要通过枚举名称(即Color.GREEN)来引用它,但是在这种情况下,只有枚举值足够了。不应该是

  case Color.RED:

等???

解决方案

不,不应该。 Java编译器足够聪明,可以知道您正在切换 Color ,因此该语言允许此快捷方式(并且保罗指出,需要它)。事实上,switch语句的整个编译取决于编译器知道你正在切换什么,因为它会根据您指定的枚举值的索引将交换机转换为跳转表。只有最近才能够打开非数值的东西,比如一个 String



相关部分语言规范位于 JLS第14.11节


  ... 
SwitchLabel:
case ConstantExpression :
case EnumConstantName:
默认值:

EnumConstantName:
标识符


如果您想了解为什么语言的设计方式是这样,那将很难客观地回答。语言设计是微妙的,您必须考虑到赋值语法是在添加枚举支持之前的年份和年份。


enum Color {RED, GREEN, BLUE};
class SwitchEnum
{
  public static void main(String[] args)
  {
    Color c = Color.GREEN;
    switch(c)
    {
      case RED:
        System.out.println("red");
        break;
      case GREEN:
        System.out.println("green");
        break;
      case BLUE:
        System.out.println("blue");
        break;
    }
  }
}

The above code compiles fine and gives the expected output.

My question is why when creating the Color reference 'c' we needed to refer it through the name of the enum (i.e. Color.GREEN) but in the case block only the enum value sufficed. Shouldn't it have been

case Color.RED:

etc???

解决方案

No, it shouldn't. The Java compiler is smart enough to know that you are switching on a Color and so the language allows for this shortcut (and as Paul notes, requires it). In fact, the whole compilation of a switch statement depends on the compiler knowing what you're switching on, since it translates the switch into a jump table based on the index of the enum value you specify. Only very recently have you been able to switch on non-numerical things like a String.

The relevant part of the language spec is in JLS Chapter 14.11:

...
SwitchLabel:
   case ConstantExpression :
   case EnumConstantName :
   default :

EnumConstantName:
   Identifier

If you're looking for insight into why the language was designed the way it was, that's going to be hard to answer objectively. Language design is nuanced, and you have to consider that the assignment syntax was written years and years before enum support was added.

这篇关于在开关情况下枚举引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆