[英]Getting enum value with reflection
I am trying to loop through and print all the ENUM values of a given Enum Class at run time. 我试图遍历并在运行时打印给定Enum类的所有ENUM值。 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. 大多数解决方案都指向使用getEnumConstants(),values()或valueOf(),但是我一直无法使它们按需工作。
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. 我能找到的最接近的问题是通过反射获取枚举的值和如何在Java中获取所有枚举值 ,但是它们显然相差甚远 ,以致于解决方案都不符合我的要求。 Below is the code I have tried and the ENUM class which is auto generated and immutable: 下面是我尝试过的代码和自动生成且不可变的ENUM类:
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)
}
and the ENUM: 和枚举:
@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);
}
desired output: 所需的输出:
TEST_1
TEST_2
Actual output: 实际输出:
TEST___A
TEST___B
Perhaps this would be easier if I understood what these auto generated classes are doing and what they are for? 如果我了解这些自动生成的类在做什么以及它们的用途,这可能会更容易?
Perhaps something like this (no reflection necessary): 也许是这样的(不需要反射):
enum MyEnum {
TEST____1("TEST_1"),
TEST____2("TEST_2");
final String value;
MyEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public void test(String[] args) {
for (MyEnum e : MyEnum.class.getEnumConstants()) {
System.out.println(e.toString() + " - " + e.getValue());
}
}
or even 甚至
enum MyEnum {
TEST____1("TEST_1"),
TEST____2("TEST_2");
final String value;
MyEnum(String value) {
this.value = value;
}
}
public void test(String[] args) {
for (MyEnum e : MyEnum.class.getEnumConstants()) {
System.out.println(e.toString() + " - " + e.value);
}
}
Finally got it: 终于明白了:
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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.