为什么一个枚举值不能在switch语句中完全限定? [英] Why can't an enum value be fully qualified in a switch statement?

查看:652
本文介绍了为什么一个枚举值不能在switch语句中完全限定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(注意:编辑的问题;以前的意图不清楚)



考虑以下代码:

  public final class Foo 
{
private enum X
{
VALUE1,VALUE2
}

public static void main(final String ... args)
{
final X x = X.VALUE1;

switch(x){
case VALUE1:
System.out.println(1);
break;
case VALUE2:
System.out.println(2);
}
}
}

此代码工作正常。 / p>

但是,如果我替换:

  case VALUE1://或VALUE2 

与:

  case X.VALUE1://或X.VALUE2 

然后编译器抱怨:


java:/path/to/Foo.java:whatever:枚举开关大小写标签必须是枚举常量的不合格名称


SO 建议一个答案与JLS的这个引用:


(需要内联常量的一个原因是switch语句在每种情况下都需要常量,没有两个这样的常量值可能相同。编译器在编译器中检查switch语句中的重复常量值TI我;类文件格式不与案例值进行符号连接。)


但是这不符合我的要求。就我而言, VALUE1 X.VALUE1 完全一样。引用的文本对我来说没有解释。



JLS中的哪个定义是枚举开关语句必须以这种方式写?

解决方案

SwitchLabel 期望一个 EnumConstantName ,它被定义为枚举常量标识符,这是不合格的


EnumConstant:

注释 opt 标识符参数 opt ClassBody opt



(note: edited question; the prior intent was not clear)

Consider this code:

public final class Foo
{
    private enum X
    {
        VALUE1, VALUE2
    }

    public static void main(final String... args)
    {
        final X x = X.VALUE1;

        switch (x) {
            case VALUE1:
                System.out.println(1);
                break;
            case VALUE2:
                System.out.println(2);
        }
    }
}

This code works fine.

However, if I replace:

case VALUE1: // or VALUE2

with:

case X.VALUE1: // or X.VALUE2

then the compiler complains:

java: /path/to/Foo.java:whatever: an enum switch case label must be the unqualified name of an enumeration constant

SO suggests an answer with this quote from the JLS:

(One reason for requiring inlining of constants is that switch statements require constants on each case, and no two such constant values may be the same. The compiler checks for duplicate constant values in a switch statement at compile time; the class file format does not do symbolic linkage of case values.)

But this does not satisfy me. As far as I am concerned, VALUE1 and X.VALUE1 are exactly the same. The quoted text does not explain it at all for me.

Where in the JLS is it defined that enum values in switch statements have to be written this way?

解决方案

SwitchLabel expects an EnumConstantName, which is defined as the enum constant identifier, which is unqualified:

EnumConstant:
Annotationsopt Identifier Argumentsopt ClassBodyopt

这篇关于为什么一个枚举值不能在switch语句中完全限定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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