Lorenzo Manucci
Lorenzo Manucci

Reputation: 880

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.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.

Upvotes: 3

Views: 1158

Answers (3)

Bohemian
Bohemian

Reputation: 424983

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.

Upvotes: 2

Harry Joy
Harry Joy

Reputation: 59660

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.

Upvotes: 1

Java_Waldi
Java_Waldi

Reputation: 934

yes, with

Enum2.EnumA.toString();

Upvotes: -1

Related Questions