java - 看来我可以*在定义之前引用一个字段*

标签 java static enums declaration

public enum MyEnum1 {

    FOO(BAR), BAR(FOO);

    private MyEnum1 other;

    private MyEnum1(MyEnum1 other) {
        this.other = other;
    }

    public MyEnum1 getOther() {
        return other;
    }

}

MyEnum1 生成错误 Cannot reference a field before it is defined,这是可以理解的,因为声明顺序在这里很重要。但是为什么下面的编译?

public enum MyEnum2 {

    FOO { public MyEnum2 getOther() { return BAR; } },
    BAR { public MyEnum2 getOther() { return FOO; } };

    public abstract MyEnum2 getOther();

}

FOO 在定义 BAR 之前引用 BAR,我错了吗?

最佳答案

重要的 JLS 部分是 thisthis

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

T is a class and an instance of T is created.

T is a class and a static method declared by T is invoked.

A static field declared by T is assigned.

A static field declared by T is used and the field is not a constant variable (§4.12.4).

T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.

The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type.

所以

FOO { public MyEnum2 getOther() { return BAR; } }, 
BAR { public MyEnum2 getOther() { return FOO; } };

您正在创建两个扩展 MyEnum2 的匿名类。

BAR 在您调用 Foo.getOther() 时最终被引用,或者某些其他代码段执行 MyEnum2.Bar 时,类型将被初始化。

关于java - 看来我可以*在定义之前引用一个字段*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18382046/

相关文章:

java - SWT CTab文件夹 : Add watermark (in case of no tabs)

java - 将数据结构从 java 传递到 perl(反之亦然)

c - 同名的两个静态变量(两个不同的文件)和外部其中一个在任何其他文件中

python - 如何子类化 Django TextChoices 以添加其他属性?

java - 如何在Java中调整绘制的椭圆形的大小?

java - 堆栈行为的正确实现

delphi - Delphi中过程的静态变量

java - 使用反射设置私有(private)字段适用于静态或最终,但不适用于静态最终(组合)

swift - 从枚举中选择随机值

java - 我应该将枚举作为参数传递还是传递其文字值