Convert integer value to matching Java Enum

前端 未结 11 1246
慢半拍i
慢半拍i 2020-12-02 08:18

I\'ve an enum like this:

public enum PcapLinkType {
  DLT_NULL(0)
  DLT_EN10MB(1)
  DLT_EN3MB(2),
  DLT_AX25(3),
  /*snip, 200 more enums, not always consecu         


        
11条回答
  •  一整个雨季
    2020-12-02 09:03

    There's a static method values() which is documented, but not where you'd expect it: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

    enum MyEnum {
        FIRST, SECOND, THIRD;
        private static MyEnum[] allValues = values();
        public static MyEnum fromOrdinal(int n) {return allValues[n];}
    }
    

    In principle, you can use just values()[i], but there are rumors that values() will create a copy of the array each time it is invoked.

提交回复
热议问题