通过反射获取枚举的值



我有一个这样声明的enum:

public enum Mode{
  RUNNING("SytemRunning"),
  STOPPED("SystemStopped"),
  IDLE("tmpIdle");
  public static String key;
  private Mode(String key){
    this.key = key;
  }
}

现在,我想通过反射得到这个enum的键(SystemRunning, SystemStopped, tmpIdle):

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

输出为:运行停止闲置

然而,我想有字符串SystemRunning, tmpIdle等。

非常感谢。

首先,您需要使您的key成为一个非静态变量。

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

那么你需要在枚举中添加一个getter方法,它将返回key

public String getKey() {
    return key;
}

,然后将for循环更改为如下内容:

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
}

添加toString()方法返回您的键,然后它将工作。你的'key'属性不应该是静态的。

如果你知道所有的枚举都有一个key属性,你也可以直接通过反射请求它

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

使用反射是没有意义的:

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

相关内容

  • 没有找到相关文章

最新更新