Java enum reverse look-up best practice

前端 未结 7 717
感情败类
感情败类 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:50

    Here is an alternative which may be even a bit faster:

    public enum Status {
        WAITING(0),
        READY(1),
        SKIPPED(-1),
        COMPLETED(5);
    
        private int code;
    
        private Status(int code) {
            this.code = code;
        }
    
        public int getCode() { return code; }
    
        public static Status get(int code) {
            switch(code) {
                case  0: return WAITING;
                case  1: return READY;
                case -1: return SKIPPED;
                case  5: return COMPLETED;
            }
            return null;
        }
    }
    

    Of course, this is not really maintainable if you want to be able to add more constants later.

提交回复
热议问题