我正在开发一个项目,如果我当前的数据中心是 DC1、DC2 或 DC3,则我需要通过查看下面提到的枚举来返回 true,而不是 DEV。如果不是则返回 false。
使用下面的代码,我可以找到我的机器名称。我的机器名称如下 -
tps1143.dc1.host.com
tps1142.dc2.host.com
tps1442.dc3.host.com
下面是我的代码 -
public enum DatacenterEnum {
DEV, DC1, DC2, DC3;
public static String forCode(int code) {
return (code >= 0 && code < values().length) ? values()[code].name() : null;
}
private static final String getHostName() {
try {
return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
} catch (UnknownHostException e) {
// log error
}
return null;
}
}
下面是我的主要方法 -
public static void main(String[] args) {
System.out.println(DatacenterEnum.getHostName());
}
我该如何继续解决这个问题?
基本上,如果我的代码运行位置位于数据中心 DC1、DC2 或 DC3,我只需要返回 true 或 false。我的机器名称包含数据中心信息。
最佳答案
Joshua Bloch 在他的 Java Classic Effective Java 的第 32 项中提到了 EnumSet
的一个有趣的用例场景。 。此项建议我们使用 EnumSet
代替位字段,这是 enum int 模式的一部分。在enum int 模式中,不同的enum
常量表示为2的幂,然后使用按位运算符组合。
正如 Puce 在他的回答中所说,你可以这样使用它:
private static final Set<DatacenterEnum> DC_DATACENTERS = EnumSet.of(DC1, DC2, DC3);
关于java - 如果我当前的数据中心位于 ENUM 中,如何返回 true 或 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21183109/