简体   繁体   中英

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

But I don't want to make a call to values() over and over again, so, I came up with something as follows:

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

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. The field has a variable initializer consisting of c, and is annotated by the same annotations as 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.

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

Incidentally, static final variables are usually named with all capitalized letters, eg VALUES , per standard Java naming conventions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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