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

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

    I would create these constants as an enumeration. Enums in Java can have their own fields and methods, which very convenient for your case. So I would do this the following way:

    enum HttpConstant {
        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 id;
    
        HttpConstant(int id) {
            this.id = id;
        }
    
        int getId() {
            return id;
        }
    }
    

    Now the iteration is easy:

    for (HttpConstant constant : HttpConstant.values()) {
        //Do something with the constant
    }
    

    This way it is also easy to add associate some new values with the constants, you just have to add new fields.

    Right now you may use reflection:

    Field[] interfaceFields = HttpConstants.class.getFields();
    for (Field field : interfaceFields) {
        int constant = field.getInt(null);
        //Do something with the field
    }
    

    However, it is better to use the approach with enums because with reflection coding errors result in runtime exceptions instead of compile-time errors.

提交回复
热议问题