How to convert String to an enum value when an enum type reference is a class <?>?
I have code that sets values ββfor an object using its configuration methods. One of the filters accepts an Enum type as a method parameter. The code looks something like this:
String value = "EnumValue1"; Method setter = getBeanWriteMethod("setMyEnumValue"); Class<?> type = setter.getParameterTypes()[0]; Object convertedValue = null; if (type.isEnum()) { convertedValue = convertToEnum(value, type); } else { convertedValue = ClassUtils.convertType(value, type); } return convertedValue; The question is what to add the convertToEnum method. I know that I could "translate it by force" by iterating the enumeration constants (or fields) of the type object, matching the value. Can I skip the simpler way to do this with Reflection? (I looked at a few examples, but did not find where the listing was known only through the class).
Above my head:
Enum<?> convertedValue = Enum.valueOf((Class<Enum>)type, value); This converts the string to an enum constant of the Enum class of type
Change Now that I have a computer, I see what actually works. Any of the following cases worked correctly without compiler warnings:
Enum<?> convertedValueA = Enum.valueOf(type, value); Enum<?> convertedValueB = Enum.valueOf(type.asSubclass(Enum.class), value); The second one calls asSubClass (), which would perform a runtime check so that type some enum class, but the valueOf() method must do this check anyway in order to work correctly.
The following gave me a compilation error:
Enum<?> convertedValueC = Enum.valueOf((Class<? extends Enum <?>>)type, value); java: Foo.java:22: <T>valueOf(java.lang.Class<T>,java.lang.String) in java.lang.Enum cannot be applied to (java.lang.Class<capture#134 of ? extends java.lang.Enum<?>>,java.lang.String) The intricacies of casting for wildcard types confuse me, so I probably tried the wrong translation. Plus, the fact that it does not have a runtime effect means that it is easily mistaken and will never know.
you can use
Class enumType = .... String name = .... Enum e = Enum.valueOf(enumType, name); eg.
import java.lang.annotation.*; public class Main { public static void main(String[] args) { Class enumType = RetentionPolicy.class; String name = "SOURCE"; Enum e = Enum.valueOf(enumType, name); System.out.println(e); } } prints
SOURCE