Java – get enumeration values through reflection

I have an enumeration 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 the key (systemrunning, systemstopped, tmpidle) of this enumeration through 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

However, I want to use strings, systemrunning, tmpidle, etc

Thank you very much for your advance

Solution

First, you need to set the key to a non - static variable

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

Then you need to add a getter method to your enumeration, which will return the key

public String getKey() {
    return key;
}

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
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>