从Enum中获取值仅在运行时获知

Scr*_*ers 4 java reflection enums

我需要从枚举中获取所有值,其类型仅在运行时才知道.我想出了以下内容,但想知道是否有人知道更好的方法:

enum TestEnum  {
  FOO,
  BAR
}

Enum[] getValuesForEnum(Class type) {
  try {
    Method m = type.getMethod("values");
    return (Enum[])m.invoke(null);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}

Class testEnum = Class.forName("TestEnum");
getValuesForEnum(testEnum);
Run Code Online (Sandbox Code Playgroud)

谢谢!

Pét*_*rök 17

改为使用可用的API:

T[] getValuesForEnum(Class<T> type) {
  return type.getEnumConstants();
}
Run Code Online (Sandbox Code Playgroud)

来自Javadoc:

返回此枚举类的元素,如果此Class对象不表示枚举类型,则返回null.

请注意,我已将您的方法转换为通用,以使其类型安全.这样,您不需要向下转换来从返回的数组中获取实际的枚举值.(当然,这使得该方法非常简单,您可以省略它并type.getEnumConstants()直接调用:-)


fin*_*nnw 8

这是Kevin Stembridge的答案的变体,它保留了类型(避免向下倾斜),同时仍然防止使用非枚举类型调用:

static <E extends Enum<E>> E[] getValuesForEnum(Class<E> clazz) {
    return clazz.getEnumConstants();
}
Run Code Online (Sandbox Code Playgroud)


maa*_*nus 5

我使用type.getEnumConstants().