Get value of enum by reflection

2019-06-20 08:38发布

问题:

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.

回答1:

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
}


回答2:

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);
  }
}


回答3:

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);
    }
}