简体   繁体   English

Java枚举中的静态(和最终)字段初始化

[英]Static (and final) field initialization in an enum in Java

Say I have this enumerated type of Colours as follows: 假设我具有以下列举的颜色类型:

public enum Colour
{
    RED, GREEN, BLUE;
}

I want to randomize a colour out of those three, following the suggestion found over there: https://stackoverflow.com/a/8114214/2736228 我想根据那边的建议从这三种颜色中随机分配一种颜色: https : //stackoverflow.com/a/8114214/2736228

But I don't want to make a call to values() over and over again, so, I came up with something as follows: 但是我不想一遍又一遍地调用values() ,所以,我想到了以下内容:

public enum Colour
{
    RED, GREEN, BLUE;

    private static final Colour[] Values = values();

    public static Colour random()
    {
        return Values[(int) (Math.random() * Values.length)];
    }
}

Question is, will it work, always? 问题是,它将始终有效吗?

What confuses me here, is that when the initialization of this private static final field occurs. 让我感到困惑的是,此private static final字段的初始化发生时。 It should be happening after the full list of enumeration is completed. 它应该在完整的枚举列表完成之后发生。 I don't see it happening anytime soon, but still, I want to make sure. 我看不到它会很快发生,但是我还是要确定。

Yes, this initialization will always work. 是的,此初始化将始终有效。 The enum constants are always listed first, and the JLS, Section 8.9.3 , guarantees that they will be initialized before any other normal static variables. 枚举常量始终列在最前面,并且JLS(第8.9.3节 )保证将在任何其他普通static变量之前对其进行初始化。

For each enum constant c declared in the body of the declaration of E, E has an implicitly declared public static final field of type E that has the same name as c. 对于E声明主体中声明的每个枚举常量c,E都有一个隐式声明的E类型的公共静态最终字段,该字段与c具有相同的名称。 The field has a variable initializer consisting of c, and is annotated by the same annotations as c. 该字段具有一个由c组成的变量初始值设定项,并由与c相同的批注进行批注。

These fields are implicitly declared in the same order as the corresponding enum constants, before any static fields explicitly declared in the body of the declaration of E. 在E声明的主体中显式声明的任何静态字段之前,以与相应的枚举常量相同的顺序隐式声明这些字段。

All static fields are initialized in order as if they were a single text block, so all of your enum constants will be initialized before Values is initialized by calling values() . 所有static字段都按顺序初始化,就好像它们是单个文本块一样,因此在通过调用values()初始化Values之前,将初始化所有枚举常量。

Incidentally, static final variables are usually named with all capitalized letters, eg VALUES , per standard Java naming conventions. 顺便说一句, static final变量通常按照标准Java命名约定以所有大写字母命名,例如VALUES

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM