简体   繁体   中英

Pass enum type as parameter

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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM