3

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
0

3 Answers 3

2
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

You need to cast it to (Class<? extends Enum<?>>)
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<?>>
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.)
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?
1

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

2 Comments

That answer :) class has a special method for enums
+1 For your help :) (but not the answer, sorry... but it is wrong)
-1

yes, with

Enum2.EnumA.toString();
answered Jul 8, 2011 at 10:48

1 Comment

he does not know Enum2 at compile time

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.