java enum receive values from string name
I have enum like:
public enum Enum2
{
ONE,TWO,THREE;
}
I can list all values like:
public static void main(String... args)
{
for (Enum2 e : Enum2.values())
{
System.out.pri开发者_运维技巧ntln(e);
}
}
Is it possible list values if I have only string name of Enum?
String enum_name="Enum2";
E.g. if in some logic like:
if (a>b)
{
enum_name="EnumA";
}
else
{
enum_name="EnumB";
}
And after I receive string name of enum - I can list all values.
Class<?> enumClazz = Class.forName("com.mycompany.Enum2");
for (Enum<?> e : ((Class<? extends Enum<?>>)enumClazz).getEnumConstants()) {
System.out.println(e.name()); // The variable "e" would be Enum2.ONE, etc
}
Thank you @Harry for helping me get this right.
Your question is not much clear to be but this is what you may want to do
Class<?> cls = Class.forName("EnumName");
if (cls.isEnum()) {
Field[] flds = cls.getDeclaredFields();
//-- your logic for fields.
}
You can use: Class.getEnumConstants()
. For more see this.
yes, with
Enum2.EnumA.toString();
精彩评论