在Java中,如何迭代接口的常量? [英] In Java, how to iterate on the constants of an interface?

查看:177
本文介绍了在Java中,如何迭代接口的常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在界面中,我以这种方式存储常量(我想知道你对这种做法的看法)。这只是一个虚拟的例子。

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 {
    /** 2XX: generally "OK" */
    public static final int HTTP_OK = 200;
    public static final int HTTP_CREATED = 201;
    public static final int HTTP_ACCEPTED = 202;
    public static final int HTTP_NOT_AUTHORITATIVE = 203;
    public static final int HTTP_NO_CONTENT = 204;
    public static final int HTTP_RESET = 205;
    public static final int HTTP_PARTIAL = 206;

        ...
}

有没有办法我可以迭代在这个接口中声明的所有常量吗?

Is there a way I can iterate over all constants declared in this interface ?

推荐答案

使用反射:

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

但无论如何,如果你可以重新设计你的类,我会建议你处理静态枚举常量结构。所以,对你的类来说,每个常量总是包含一个int值:

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;
    }
}

然后,循环上面:

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

因此,避免访问反射API。

Thus, avoiding the access to the reflection API.

这篇关于在Java中,如何迭代接口的常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆