Is there a way to get the enum type from and ordinal value?

java

Solution

The simplest approach is:

xyzType xyz = xyzType.values()[ordinalValue];

However, this will create a new array each time. An alternative would be to cache it within the enum:

public enum Xyz {
    Foo, Bar;

    private static final Xyz[] VALUES = values();

    public Xyz fromOrdinal(int ordinal) {
        return VALUES[ordinal];
    }
}

Problem

What i mean by that is suppose ``` Enum xyzType { A, B, C, D } ``` I know I can get the ordinal a value of C, by doing xyzType.C.ordinal() which is 2. Suppose I just have 2, I would to get the enum type C. I can't seem to find anything in the enum API that would do this. I would prefer not to have a huge switch statement to compare each ordinal value and return the enum. Is there a better to do this ?

Original source