如何创建通用枚举转换器?

mem*_*und 2 java generics enums

我想编写一个可以像这样使用的通用类 new EnumConverter(MyEnum.class);

但是我必须编写那个类,以便它可以与对enum.values()?

public class EnumConverter {
    public EnumConverter(Class<Enum<?>> type) {
        this.type = type;
    }

    public EnumConverter convert(String text) {
        //error: Type mismatch: cannot convert from element type capture#1-of ? to Enum<?>
        for (Enum<?> candidate : type.getDeclaringClass().getEnumConstants()) {
            if (candidate.name().equalsIgnoreCase(text)) {
                return candidate;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

flo*_*flo 5

您的方法 Convert 的返回类型是错误的:应该是Enum而不是EnumConverter。然后您不必调用getDeclaringClass()而是使用Class您已有的类型。

我建议采用一种更通用的方法:

public static class EnumConverter<T extends Enum<T>>
{

    Class<T> type;

    public EnumConverter(Class<T> type)
    {
        this.type = type;
    }

    public Enum<T> convert(String text)
    {
        for (Enum<T> candidate : type.getEnumConstants()) {
            if (candidate.name().equalsIgnoreCase(text)) {
                return candidate;
            }
        }

        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)


lum*_*umo 5

您的问题不一致且代码无效:1)this.type 未定义为字段 2)您定义 convert 以返回EnumConverter但返回一个Enum

要从文本返回枚举的枚举值,您不需要通用的东西。您只需使用:

Enum.valueOf(MyEnum.class, "TWO")
Run Code Online (Sandbox Code Playgroud)