Pass enum type as parameter

MauriceNino :

I want to create a method, that:

  • Takes the type of an enum and a String as arguments
    • The String is the name of one specific enum instance
  • Returns the enum instance that fits that name.

What I have tried:

In class TestUtil.java:

public static <E extends Enum<E>> E mapToEnum(Enum<E> mappingEnum, String data) {

    return mappingEnum.valueOf(E, data); // Not working, needs Class of Enum and String value
}

The enum:

public enum TestEnum {
    TEST1("A"),
    TEST2("B");

    private String value;

    private TestEnum(String value) {
        this.value = value;
    }
}

How it should work (For example in main method):

TestEnum x = TestUtil.mapToEnum(TestEnum.class, "TEST1"); // TEST1 is the name of the first enum instance

The problem is, that I can't figure out what I need to pass into the mapToEnum method, so that I can get the valueOf from that Enum.

Fenio :

If the code you provided is acceptable:

public static <E extends Enum<E>> E mapToEnum(Enum<E> mappingEnum, String data) {

    return mappingEnum.valueOf(E, data); // Not working, needs Class of Enum and String value
}

Then all you have to do is fix it.

Here's the code I tested:

static <T extends Enum<T>> T mapToEnum(Class<T> mappingEnum, String data) {
    return Enum.valueOf(mappingEnum, data);
}

Usage:

@Test
public void test() {
    TestEnum myEnum = mapToEnum(TestEnum.class, "TEST1");
    System.out.println(myEnum.value); //prints "A"
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=322901&siteId=1