Java enum reverse look-up best practice

前端 未结 7 698
感情败类
感情败类 2020-12-04 15:07

I saw it suggested on a blog that the following was a reasonable way to do a \"reverse-lookup\" using the getCode(int) in a Java enum:

public en         


        
7条回答
  •  抹茶落季
    2020-12-04 15:39

    Maps.uniqueIndex from Google's Guava is quite handy for building lookup maps.

    Update: Here is an example using Maps.uniqueIndex with Java 8:

    public enum MyEnum {
        A(0), B(1), C(2);
    
        private static final Map LOOKUP = Maps.uniqueIndex(
                    Arrays.asList(MyEnum.values()),
                    MyEnum::getStatus
        );    
    
        private final int status;
    
        MyEnum(int status) {
            this.status = status;
        }
    
        public int getStatus() {
            return status;
        }
    
        @Nullable
        public static MyEnum fromStatus(int status) {
            return LOOKUP.get(status);
        }
    }
    

提交回复
热议问题