Java – when the enumeration type reference is class How do I convert a string to an enumerated value?

I have code to set values on objects using the setter method One of the setters takes enum type as a method parameter The code looks 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 put in the converttoenum method I know I can "force it" by iterating over the enumeration constant (or field) of a type object to match the value Did I ignore the simpler method of using reflection? (I looked at several examples, but I didn't find any enumeration that can only be known through class)

Solution

Off my head:

Enum<?> convertedValue = Enum.valueOf((Class<Enum>)type,value);

This converts the string to an enum constant of the enum class of type

Editor: now I have a computer for convenience. I can see what it actually does Without compiler warnings, any of the following conditions work correctly:

Enum<?> convertedValueA = Enum.valueOf(type,value);
Enum<?> convertedValueB = Enum.valueOf(type.asSubclass(Enum.class),value);

The second call, assubclass (), performs a runtime check to ensure that the type is some enumeration class, but the valueof () method must be checked to work properly

The following gives 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 complexity of projecting wildcard types puzzles me, so I may have tried the wrong actors In addition, the fact that it has no runtime effect means that it is easy to make mistakes and will never be found

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>