In Java, how to iterate on the constants of an interface?

前端 未结 6 1246
心在旅途
心在旅途 2021-02-07 12:51

in an interface, I store constants in this way (I\'d like to know what you think of this practice). This is just a dummy example.

interface HttpConstants {
    /         


        
6条回答
  •  野的像风
    2021-02-07 13:19

    I'd like to know what you think of this practice

    Consider using an enum instead of an interface with constants.

    enum HttpResultCode {
        HTTP_OK(200),
        HTTP_CREATED(201),
        HTTP_ACCEPTED(202),
        HTTP_NOT_AUTHORITATIVE(203),
        HTTP_NO_CONTENT(204),
        HTTP_RESET(205),
        HTTP_PARTIAL(206);
    
        private final int code;
    
        private HttpResultCode(int code) {
            this.code = code;
        }
    
        public int getCode(int code) {
            return code;
        }
    
        public static HttpResultCode forCode(int code) {
            for (HttpResultCode e : HttpResultCode.values()) {
                if (e.code == code) {
                    return e;
                }
            }
    
            throw new IllegalArgumentException("Invalid code: " + code);
        }
    }
    

提交回复
热议问题