从具有 Class<?扩展枚举 > 对象

Getting Enum from an integer having a Class<? extends Enum> object

我已经看到 this 如果我有一个字符串而不是整数,这是一个非常好的解决方案,但如果我只有特定枚举的 class 对象和一个整数,该怎么做我得到特定的枚举常量实例?

好像找到答案了:

((Class<? extends Enum>)clazz).getEnumConstants()[index]

尽管对于任何正在寻找它的人来说,您应该考虑遵循@Daniel Pryden 的回答,因为在我能想到的大多数用例中使用它很可能是不好的做法。

依赖 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,您可以自己构建查找 table 并将其存储在 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 对象。