MauriceNino
MauriceNino

Reputation: 6757

Pass enum type as parameter

I want to create a method, that:

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.

Upvotes: 4

Views: 679

Answers (3)

drekbour
drekbour

Reputation: 3091

Strongly suggest using Apache commons-lang library for boiler plate function like this ...

TestEnum x = EnumUtils.getEnum(TestEnum.class, "TEST1");

... which is exactly the code @Fenio demonstrates but handles null or wrong input with a null instead of throwing an Exception.

If you didn't know about this then check out what the rest of the lang3 library holds. I view it as a de-facto standard, saving millions of devs from re-writing minor plumbing utilities.

Upvotes: 1

Fenio
Fenio

Reputation: 3635

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"
}

Upvotes: 3

Arpit Asati
Arpit Asati

Reputation: 140

This is how you can iterate the enum class value and match with the parameter you have passed in the method, please check the below-mentioned code.

  enum TestEnum {
    TEST1("test1"),
    TEST2("test2");

   private String value;

   private TestEnum(String value) {
       this.value = value;
   }
   public String getName() {
       return value;
   }
   public static TestEnum mapToEnum(String data) {
       for (TestEnum userType : TestEnum.values()) {
           if (userType.getName().equals(data)) {
               return userType;
           }
       }
       return null;
   }
}

Upvotes: 0

Related Questions