这与Java类似但不完全相同:使用反射实例化枚举
我有一个Map, FooHandler>我想用来映射Enums(我不关心哪种类型,或者即使它们是同一类型,只要它们是枚举常量)到我的FooHandler类。
我想使用我阅读的文本文件填充此地图。我可以让它工作,但我有两个警告我想绕过:
static private > E getEnum(String enumFullName) {
// see https://stackoverflow.com/questions/4545937/
String[] x = enumFullName.split("\.(?=[^\.]+$)");
if (x.length == 2)
{
String enumClassName = x[0];
String enumName = x[1];
try {
Class cl = (Class)Class.forName(enumClassName);
// #1
return Enum.valueOf(cl, enumName);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return null;
}
public void someMethod(String enumName, String fooHandlerName)
{
FooHandler fooHandler = getFooHandler(fooHandlerName);
Enum e = getEnum(enumName);
// #2
map.put(e, fooHandler);
}
警告#1:未经检查的演员
警告#2:枚举是一种原始类型。
我得到#1并且我可以发出警告,但我似乎无法击败警告#2;我试过Enum>,这只是给我一个关于泛型类型捕获绑定不匹配的错误。
更糟糕的替代实施:
在我的>泛型返回值之前,我尝试返回Enum并且它不起作用;我收到了这些警告/错误:
static private Enum> getEnum(String enumFullName) {
...
Class> cl = (Class>)Class.forName(enumClassName);
// 1
return Enum.valueOf(cl, enumName);
// 2
}
警告:
- Type safety: Unchecked cast from Class to Class
- Enum is a raw type. References to generic type Enum should be parameterized
- Enum is a raw type. References to generic type Enum should be parameterized
- Unnecessary cast from Class to Class>
错误:
- Type mismatch: cannot convert from capture#5-of ? to Enum>
- Type safety: Unchecked invocation valueOf(Class, String) of the generic method
valueOf(Class, String) of type Enum
- Bound mismatch: The generic method valueOf(Class, String) of type Enum is not
applicable for the arguments (Class, String). The inferred type capture#5-of ? is not
a valid substitute for the bounded parameter >
还有这个:
static private Enum> getEnum(String enumFullName) {
...
Class> cl = (Class>)Class.forName(enumClassName);
// 1
return Enum.valueOf(cl, enumName);
// 2
警告:Type safety: Unchecked cast from Class to Class>
错误:Bound mismatch: The generic method valueOf(Class, String) of type Enum is not applicable for the arguments (Class>, String). The inferred type Enum> is not a valid substitute for the bounded parameter >