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

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

问题描述

(注意:编辑过的问题;先前的意图不明确)

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

考虑这个代码:

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);
        }
    }
}

此代码工作正常.

但是,如果我替换:

case VALUE1: // or VALUE2

与:

case X.VALUE1: // or X.VALUE2

然后编译器抱怨:

java:/path/to/Foo.java:whatever: 枚举 switch case 标签必须是枚举常量的非限定名称

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

SO 用来自 JLS 的这句话提出答案:

(需要内联常量的一个原因是 switch 语句在每种情况下都需要常量,并且没有两个这样的常量值可能相同.编译器在编译时检查 switch 语句中的重复常量值;类文件格式不做大小写值的符号链接.)

(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.)

但这并不能让我满意.就我而言,VALUE1X.VALUE1 完全相同.引用的文字根本没有为我解释.

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.

在 JLS 中的何处定义 switch 语句中的 enum 值必须以这种方式编写?

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

推荐答案

SwitchLabel 需要 EnumConstantName,定义为枚举常量标识符,这是不合格的:

枚举常量:
注释opt 标识符参数opt ClassBodyopt

EnumConstant:
Annotationsopt Identifier Argumentsopt ClassBodyopt

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

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