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.println(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.
wattostudios
8,78613 gold badges45 silver badges58 bronze badges
asked Jul 8, 2011 at 10:44
Lorenzo Manucci
8802 gold badges15 silver badges28 bronze badges
3 Answers 3
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.
answered Jul 8, 2011 at 11:01
Sign up to request clarification or add additional context in comments.
4 Comments
Harry Joy
You need to cast it to
(Class<? extends Enum<?>>)Harry Joy
output of run:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from Class<capture#1-of ?> to Class<? extends Enum<?>>Tom Hawtin - tackline
I'd use
asSubclass instead of the dodgy cast. (Actually, I'd try to avoid getting myself in a mess that requires reflection in the first place.)Bohemian
how would you use asSubClass? it accepts a Class instance as parameter, but we don't know what class it is. could you post a fragment here to show what you had in mind?
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.
answered Jul 8, 2011 at 10:48
Harry Joy
59.8k30 gold badges167 silver badges211 bronze badges
yes, with
Enum2.EnumA.toString();
answered Jul 8, 2011 at 10:48
Java_Waldi
9442 gold badges13 silver badges30 bronze badges
1 Comment
user102008
he does not know Enum2 at compile time
lang-java