vendredi 15 décembre 2017

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. 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?





Aucun commentaire:

Enregistrer un commentaire