通过反射获取枚举的值 [英] Get value of enum by reflection

查看:515
本文介绍了通过反射获取枚举的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样声明的枚举:

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

现在,我想拿出钥匙(SystemRunning ,通过反射对此枚举进行枚举:

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

输出为:
正在运行
已停止
IDLE

the output is: RUNNING STOPPED IDLE

但是,我想使用Strings SystemRunning,tmpIdle等。

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

谢谢

推荐答案

首先,您需要创建密钥非静态变量。

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

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

然后您需要在枚举中添加getter方法,返回 key

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
}

这篇关于通过反射获取枚举的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆