Enum.valueOf(Class<T> enumType, String name) 问题 [英] Enum.valueOf(Class<T> enumType, String name) question
问题描述
我正在尝试解决与动态枚举查找相关的编译错误(绑定不匹配:...").
I am trying to get around a compile error ("Bound mismatch: ...") relating to dynamic enum lookup.
基本上我想实现这样的目标:
Basically I want to achieve something like this:
String enumName = whatever.getEnumName();
Class<? extends Enum<?>> enumClass = whatever.getEnumClass();
Enum<?> enumValue = Enum.valueOf(enumClass, enumName);
无论我做什么,我总是以编译错误告终.老实说,泛型和枚举对我来说非常令人难以置信...
Whatever I do, I always end up with that compile error. Honestly, generics and enums are quite mindboggling to me...
我在这里做错了什么?
推荐答案
我认为除非您有权访问类型变量(通过类型或方法签名),否则它不会完全像这样工作.问题是Enum.valueOf
的方法签名:
I think it won't work exactly like this unless you have access to a type variable (through either a type or method signature). The problem is the method signature of Enum.valueOf
:
public static <T extends Enum<T>> T valueOf(
Class<T> enumType,
String name
);
没有类型变量就无法获得 T.但是如果你愿意抑制一些编译器警告,你可以这样做:
There's no way to get a T without a type variable. But you can do it like this if you're willing to suppress some compiler warnings:
public enum King{
ELVIS
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(final String[] args){
final Class<? extends Enum> enumType = King.class;
final Enum<?> theOneAndOnly = Enum.valueOf(enumType, "ELVIS");
System.out.println(theOneAndOnly.name());
}
输出:
猫王
这篇关于Enum.valueOf(Class<T> enumType, String name) 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!