簡體   English   中英

從具有類的整數獲取枚舉<? extends Enum>目的

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

我已經看到是一個非常好的解決方案,如果我有一個字符串而不是整數,但如果我只有特定枚舉的類對象和一個整數,我該如何獲得特定的枚舉常量實例?

似乎找到了答案:

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

然后,每當你想獲得thingIdMyThing ,只需調用getThingId()方法:

void doSomething(MyThing thing) {
  System.out.printf("Got MyThing object %s with ID %d\n",
    thing.name(), thing.getThingId());
}

如果您希望能夠查找一個MyThingthingId ,你可以自己建立一個查找表,並將其存儲在一個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對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM