Java 枚举值字段在定义之外不可访问

标签 java enums

在以下代码中,Colours 枚举 GREEN 值的成员字段在枚举定义之外无法访问:

public class Test {

    enum Colours {
        RED,
        GREEN {
            public static final int hex = 0x00ff00;
            public final int hex2 = 0x00ff00;  // Try it without static, just in case...

            void f() {
                System.out.println(hex);    // OK
                System.out.println(hex2);   // OK
            }
        },
        BLUE
    }

    public static void main(String[] args) {
        System.out.println(Colours.GREEN.hex);      // COMPILE ERROR
        System.out.println(Colours.GREEN.hex2);     // COMPILE ERROR
    }
}

有问题的行会导致以下编译器错误:

Error:(38, 41) java: cannot find symbol
  symbol:   variable hex
  location: variable GREEN of type Test.Colours

知道为什么这不起作用吗?我认为 Java 标准禁止这样做,但为什么呢?

最佳答案

根据 JLS §8.9.1. Enum Constants enum 常量主体受适用于匿名类的规则控制,这些规则限制了字段和方法的可访问性:

The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type. The class body is governed by the usual rules of anonymous classes; in particular it cannot contain any constructors. Instance methods declared in these class bodies may be invoked outside the enclosing enum type only if they override accessible methods in the enclosing enum type (§8.4.8).

关于Java 枚举值字段在定义之外不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55393152/

相关文章:

java - JFreeChart:TimeSeries 图表上的多个时间序列显示不正确

java - PyDev:同一项目中的 Jython 模块和 Java 类

java - 在泛型上调用 Enum.values()

java - 查询 JDBC Java

java - 如何在 Lambda 表达式中定义 Intent

java - 忽略聊天中的 ChatState 数据包并在 SMACK 控制台中登录聊天状态

java - 如何在 Java 中使用 Switch 和 Enum 参数(不是 ENUM VALUE)?

c# - 字符串的键(枚举)

c++ - 使用枚举重载函数

mysql - 使用 BIT 值将多列合并为一列