通过反射获得枚举值 [英] Getting enum value with reflection

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

问题描述

我试图遍历并在运行时打印给定Enum类的所有ENUM值.但是我似乎只能返回与值关联的常量.大多数解决方案都指向使用getEnumConstants(),values()或valueOf(),但是我一直无法使它们按需工作.

I am trying to loop through and print all the ENUM values of a given Enum Class at run time. But I can only seem to return the constants associated to the values. Most solutions point to using getEnumConstants(), values(), or valueOf(), but I have been unable to get them to work as desired.

我能找到的最接近的问题是通过反射获取枚举的值 how-to-get-all-enum-values -in-java ,但显然它们之间的差异足以使解决方案不符合我的要求.下面是我尝试过的代码和自动生成且不可变的ENUM类:

The closest questions I could find are Get value of enum by reflection and how-to-get-all-enum-values-in-java, but they apparently are different enough that the solutions did not fit my requirements. Below is the code I have tried and the ENUM class which is auto generated and immutable:

Class cls = Class.forName("TestEnum");
for (Object obj : cls.getEnumConstants()) 
{
    System.out.println(obj.toString()); //prints TEST___A (not TEST_1)
    System.out.println(Enum.valueOf(cls, obj.toString()));  //prints TEST___A (not TEST_1)
}

和枚举:

@XmlType(name = "TestEnum")
@XmlEnum
public enum TestEnum {

    @XmlEnumValue("TEST_1")
    TEST___A("TEST_1"),
    @XmlEnumValue("TEST_2")
    TEST___B("TEST_2");
    private final String value;

    TestEnum(String v) {
        value = v;
    }

    public String value() {
        return value;
    }

    public static TestEnum fromValue(String v) {
        for (TestEnum c: TestEnum.values()) {
            if (c.value.equals(v)) {
                return c;
            }
        }
        throw new IllegalArgumentException(v);
    }

所需的输出:

TEST_1
TEST_2

实际输出:

TEST___A
TEST___B

如果我了解这些自动生成的类在做什么以及它们的用途,这也许会更容易些?

Perhaps this would be easier if I understood what these auto generated classes are doing and what they are for?

推荐答案

最后得到它:

Class cls = Class.forName("TestEnum");
for (Object obj : cls.getEnumConstants()) {
   try {
       Method m = cls.getMethod("value", null);
       System.out.println(m.invoke(obj, null));
   } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
       System.out.println("could not find enum");
   }
}

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

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