Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of enum by reflection

I have an enum declared like this:

public enum Mode{
  RUNNING("SytemRunning"),
  STOPPED("SystemStopped"),
  IDLE("tmpIdle");

  public static String key;

  private Mode(String key){
    this.key = key;
  }
}

Now, I want to get out the keys(SystemRunning, SystemStopped, tmpIdle) for this enum by reflection:

Class<?> c = Class.forName("Mode");
Object[] objects = c.getEnumConstants();
// now this is not what I want, but almost
for(Object obj : objects){
  System.out.println("value : " + obj);
}

the output is: RUNNING STOPPED IDLE

However, I'd like to have the Strings SystemRunning, tmpIdle etc..

Thank you very much in advance.

like image 867
blaster Avatar asked Jun 17 '14 09:06

blaster


3 Answers

Firstly, you need to make your key a non-static variable.

private String key; // I made it private on purpose

Then you need to add a getter method in your enum which will return the key

public String getKey() {
    return key;
}

and then change your for loop to something like this.

for (Object obj : objects) {
    Class<?> clzz = obj.getClass();
    Method method = clzz.getDeclaredMethod("getKey");
    String val = (String) method.invoke(obj);
    System.out.println("value : " + val); // prints SytemRunning, SystemStopped and tmpIdle
}
like image 111
Rahul Avatar answered Sep 18 '22 17:09

Rahul


Add a method toString() that returns your key, then it will work. Your 'key' property shouldn't be static.

If you know that all your enums have a key property, you can ask for it directly by reflection too.

public enum Mode{
  RUNNING("SytemRunning"),
  STOPPED("SystemStopped"),
  IDLE("tmpIdle");

  public String key;

  private Mode(String key) {
    this.key = key;
  }
  public String toString() {
    return this.key;
  }
}

Get 'key' with reflection:

Class<?> c = Class.forName("Mode");
Object[] objects = c.getEnumConstants();
// now this is not what I want, but almost
for(Object obj : objects) {
  try {
    Field keyField = obj.getClass.getDeclaredField("key");
    keyField.setAccessible(true); // if it is private for example.
    System.out.printn("value : " + keyField.get(obj);
  } catch (NoSuchFieldException e) {
    // fallback to toString()
    System.out.println("value : " + obj);
  }
}
like image 20
Cyrille Pontvieux Avatar answered Sep 21 '22 17:09

Cyrille Pontvieux


There is no point using reflection for this:

public interface EnumWithValue<T> {
    T getValue();
}

public enum Mode implements EnumWithValue<String> {
    RUNNING("SytemRunning"),
    STOPPED("SystemStopped"),
    IDLE("tmpIdle");

    private final String value;

    private Mode(String value) {
        this.value = value;
    }

    @Override
    public String getValue() {
        return value;
    }
}

public void test() {
    try {
        Class<? extends EnumWithValue<String>> clazz = (Class<? extends EnumWithValue<String>>) Class.forName("Mode");
        EnumWithValue<String>[] values = clazz.getEnumConstants();

        for (EnumWithValue<String> enumWithValue : values) {
            System.out.print(enumWithValue + " = " + enumWithValue.getValue());
        }
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(ConverterEnum.class.getName()).log(Level.SEVERE, null, ex);
    }
}
like image 24
ChRoNoN Avatar answered Sep 17 '22 17:09

ChRoNoN