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

前端 未结 6 1314
心在旅途
心在旅途 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:18

    Using reflection:

    Field[] interfaceFields=HttpConstants.class.getFields();
    for(Field f:interfaceFields) {
       //do something
    }
    

    But anyway, if you can redesign your class, I would recomend you to handle a static enum constants construction. So, suposing your class will contain always an int value for every constant:

    enum HttpConstants {
    
        HTTP_OK(200), HTTP_CREATED(201), HTTP_ACCEPTED(202),
        HTTP_NOT_AUTHORITATIVE(203),HTTP_NO_CONTENT(204), 
        HTTP_RESET(205), HTTP_PARTIAL(206) /* ... */;
    
        private int value;
    
        HttpConstants(int aValue) {
            value=aValue;
        }
    
        public int getValue() {
            return value;
        }
    }
    

    Then, to loop on it:

        for(HttpConstants val: HttpConstants.values()) {
            int value=val.getValue();
                //...
        }
    

    Thus, avoiding the access to the reflection API.

提交回复
热议问题