当枚举类型引用是Class <?>时,如何将String转换为枚举值?

Sam*_*erg 6 java reflection enums

我有使用setter方法在对象上设置值的代码.其中一个setter将Enum类型作为方法参数.代码看起来像这样:

    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;
Run Code Online (Sandbox Code Playgroud)

问题是该convertToEnum方法应该放什么.我知道我可以通过迭代对象的枚举常量(或字段)来"强制它" type,匹配值.我是否忽略了使用Reflection进行更简单的方法?(我查看了几个例子,但没有找到任何枚举只能通过Class知道的地方).

Adr*_*onk 22

脱离我的头顶:

  Enum<?> convertedValue = Enum.valueOf((Class<Enum>)type,  value);
Run Code Online (Sandbox Code Playgroud)

这会将字符串转换为类型的Enum类的枚举常量

编辑:现在我有一台电脑方便,我可以看到实际上有什么用.在没有编译器警告的情况下,以下任一情况都正确运行:

Enum<?> convertedValueA = Enum.valueOf(type, value);
Enum<?> convertedValueB = Enum.valueOf(type.asSubclass(Enum.class), value);
Run Code Online (Sandbox Code Playgroud)

第二个调用asSubClass(),它会进行运行时检查以确保它type是一些枚举类,但该valueOf()方法必须进行检查才能正常工作.

以下给了我一个编译错误:

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)
Run Code Online (Sandbox Code Playgroud)

投射到通配符类型的复杂性使我感到困惑所以我可能尝试过错误的演员.此外,它没有运行时效果这一事实意味着它很容易弄错,永远不会发现.