简体   繁体   English

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

[英]How to convert String to enum value when enum type reference is a Class<?>?

I have code which is setting values on an object using its setter methods. 我有使用setter方法在对象上设置值的代码。 One of the setters takes an Enum type as the method parameter. 其中一个setter将Enum类型作为方法参数。 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 put in the convertToEnum method. 问题是在convertToEnum方法中放入什么。 I know I could "brute force it" by iterating the enum constants (or the fields) of the type object, matching the value. 我知道我可以通过迭代type对象的枚举常量(或字段)来“强制它”,匹配值。 Am I overlooking a simpler way to do it using Reflection? 我是否忽略了使用Reflection进行更简单的方法? (I looked at several examples, but didn't find any where the enum was only know via Class). (我查看了几个例子,但没有找到任何枚举只能通过Class知道的地方)。

Off the top of my head: 脱离我的头顶:

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

This will convert a string to an enum constant of the Enum class of type 这会将字符串转换为类型的Enum类的枚举常量

Edit : Now that I have a computer handy, I can see what actually works. 编辑 :现在我有一台电脑方便,我可以看到实际上有什么用。 Either of the below cases ran 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 do a runtime check to ensure that type is some enum class, but the valueOf() method has to make that check anyway in order to work correctly. 第二个调用asSubClass(),它会进行运行时检查以确保该type是一些枚举类,但valueOf()方法必须进行检查才能正常工作。

The following gave me a compile 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 to wildcard types confuses me so I've probably tried the wrong cast. 投射到通配符类型的复杂性使我感到困惑所以我可能尝试过错误的演员。 Plus the fact that it has no runtime effect means that it's easy to get it wrong and never find out. 此外,它没有运行时效果这一事实意味着它很容易弄错,永远不会发现。

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
Enum.valueOf(yrEnum, myString)

Returns the enum where myString is the name of the enum instance you want. 返回枚举,其中myString是所需枚举实例的名称。 And yrEnum.values() returns an array of all the different possible Enums instances. yrEnum.values()返回所有不同可能的Enums实例的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Java中将字符串值转换为Enum? - How to convert string value into Enum in Java? 将字符串转换为等效的枚举值 - Convert String to equivalent Enum value 使用反射将字符串转换为枚举值,其中枚举类型可以是多个 - Convert string to enum value using reflection, where the enum type can be any of several 休眠如何在Map中映射Enum键和值 <enum,enum> 作为一个字符串 - Hibernate how to map Enum key and value in Map<enum,enum> as a String 如何访问另一个类的枚举类型? 有没有一种方法可以将字符串(映射键)用作期望枚举的方法的参数 <?> 类型? - How to access enum type of another class? Is there a way to use a String (a map key) as an argument of a method expecting Enum<?> type? 如何将枚举值转换为int? - How to convert enum value to int? 如何将解析的字符串转换为枚举类型作为 java 中的参数 - How to convert parsed string into enum type as an argument in java 如何将 Java String 转换为 Enum ConverterFactory 类到 Kotlin - How to convert Java String to Enum ConverterFactory class to Kotlin 将枚举列表转换为具有匹配枚举值的逗号分隔字符串 - Convert Enum list to comma separated String with matching Enum value JPA条件,将枚举类型转换为字符串 - Jpa criteria, convert enum type to string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM