Get Values from Enum Known Only At Runtime

2019-03-31 11:51发布

I need to get all the values from an enum, whose type will only be known at runtime. I've come up with the following, but would like to know if anyone knows a better way:

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);

Thanks!

4条回答
三岁会撩人
2楼-- · 2019-03-31 12:30

Here's a variant of Kevin Stembridge's answer that preserves the type (avoiding downcasts), whilst still guarding against being called with a non-enum type:

static <E extends Enum<E>> E[] getValuesForEnum(Class<E> clazz) {
    return clazz.getEnumConstants();
}
查看更多
混吃等死
3楼-- · 2019-03-31 12:32

Use the available API instead:

T[] getValuesForEnum(Class<T> type) {
  return type.getEnumConstants();
}

From the Javadoc:

Returns the elements of this enum class or null if this Class object does not represent an enum type.

Note that I have turned your method into generic to make it typesafe. This way you need no downcasts to get the actual enum values from the returned array. (Of course, this makes the method so trivial that you can omit it and call type.getEnumConstants() directly :-)

查看更多
放荡不羁爱自由
4楼-- · 2019-03-31 12:32

I think this works:

Enum<?>[] getValuesForEnum(Class<Enum<?>> enumType) {
    return enumType.getEnumConstants();
}
查看更多
Bombasti
5楼-- · 2019-03-31 12:36

I use type.getEnumConstants().

查看更多
登录 后发表回答