从枚举获取值仅在运行时才能知道 [英] Get Values from Enum Known Only At Runtime

查看:117
本文介绍了从枚举获取值仅在运行时才能知道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从枚举中获取所有的值,其类型只能在运行时被知道。我想出了以下几点,但是想知道有没有人知道更好的方法:

 枚举TestEnum {
FOO,
BAR
}

枚举[] getValuesForEnum(类类型){
try {
方法m = type.getMethod(values );
return(Enum [])m.invoke(null);
} catch(Exception e){
throw new RuntimeException(e);
}
}

类testEnum = Class.forName(TestEnum);
getValuesForEnum(testEnum);

谢谢!

解决方案

使用可用的API:

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

Javadoc


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


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


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!

解决方案

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

这篇关于从枚举获取值仅在运行时才能知道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆