【发布时间】:2015-11-02 04:41:12
【问题描述】:
我已经看到this 如果我有一个字符串而不是整数,这是一个非常好的解决方案,但如果我只有特定枚举的类对象和一个整数,我该如何获取特定的枚举常量实例?
【问题讨论】:
标签: java reflection enums
我已经看到this 如果我有一个字符串而不是整数,这是一个非常好的解决方案,但如果我只有特定枚举的类对象和一个整数,我该如何获取特定的枚举常量实例?
【问题讨论】:
标签: java reflection enums
依赖 Java 枚举常量的序数值是不好的做法 - 很容易意外地重新排序它们,这会破坏您的代码。更好的解决方案是简单地提供您自己的整数,您可以使用它来代替:
public enum MyThing {
FOO(1),
BAR(2),
BAZ(3);
private final int thingId;
private MyThing(int thingId) {
this.thingId = thingId;
}
public int getThingId() {
return thingId;
}
}
然后,当您想从MyThing 中获取thingId 时,只需调用getThingId() 方法即可:
void doSomething(MyThing thing) {
System.out.printf("Got MyThing object %s with ID %d\n",
thing.name(), thing.getThingId());
}
如果您希望能够通过thingId 查找MyThing,您可以自己构建查找表并将其存储在static final 字段中:
private static final Map<Integer, MyThing> LOOKUP
= createLookupMap();
private static Map<Integer, MyThing> createLookupMap() {
Map<Integer, MyThing> lookupMap = new HashMap<>();
for (MyThing thing : MyThing.values()) {
lookupMap.put(thing.getThingId(), thing);
}
return Collections.unmodifiableMap(lookupMap);
}
public static MyThing getThingById(int thingId) {
MyThing result = LOOKUP.get(thingId);
if (result == null) {
throw new IllegalArgumentException(
"This is not a valid thingId: " + thingId);
}
return result;
}
如果你最终有很多枚举类,并且你想对它们中的每一个做类似的事情,你可以为此定义一个接口:
public interface Identifiable {
int getId();
}
然后让你的枚举实现那个接口:
public enum MyThing implements Identifiable {
...
@Override
public int getId() {
return thingId;
}
}
然后您可以构建一个可重用的机制来根据其 ID 查找 Identifiable 对象。
【讨论】:
似乎找到了答案:
((Class<? extends Enum>)clazz).getEnumConstants()[index]
尽管对于任何寻找它的人,您都应该考虑遵循@Daniel Pryden 的回答,因为在我能想到的大多数用例中使用它很可能是不好的做法。
【讨论】: