Reputation: 836
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.
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)
}
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?
Upvotes: 8
Views: 14742
Reputation: 836
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");
}
}
Upvotes: 13
Reputation: 65811
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);
}
}
Upvotes: 0