在一个接口中,我以这种方式存储常量(我想知道你对这种做法的看法)。这只是一个虚拟的例子。在Java中,如何迭代接口的常量?
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;
...
}
有没有一种方法可以迭代在此接口中声明的所有常量?
意见:enums _do_在现代代码中提供了很多好处,强烈推荐。但不是所有情况。字符串与“标识符”(例如,属性名称,属性键,JSF视图ID,JPA命名的查询名称和查询占位符,安全角色...)有很多相似之处。问题:字符串文字很容易输入错误,并且没有编译时间检查。我更喜欢将所有这样的字符串声明为常量,通常在枚举中。但是,将它们用作**注释参数**时,不允许使用枚举,并且仍然需要回退到类似于您的代码的'public static final String's。 – fr13d 2014-06-25 15:32:29