这与Java类似但不完全相同:使用反射实例化枚举
我有一个Map<Enum<?>, FooHandler>
我想用来将Enum
s(我不在乎是哪种类型,即使它们是相同的类型,只要它们是枚举常量)就可以映射到我的FooHandler
类。
我想使用我阅读的文本文件填充此地图。我可以使它正常工作,但是我有两个警告要解决:
static private <E extends Enum<E>> 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<E> cl = (Class<E>)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<?>
,这给了我关于通用类型捕获绑定不匹配的错误。
更糟糕的替代实现:在我的<E extends Enum<E>>
通用返回值之前,我尝试返回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<capture#3-of ?> to Class<Enum>
- Enum is a raw type. References to generic type Enum<E> should be parameterized
- Enum is a raw type. References to generic type Enum<E> should be parameterized
- Unnecessary cast from Class<capture#3-of ?> to Class<?>
错误:
- Type mismatch: cannot convert from capture#5-of ? to Enum<?>
- Type safety: Unchecked invocation valueOf(Class<Enum>, String) of the generic method
valueOf(Class<T>, String) of type Enum
- Bound mismatch: The generic method valueOf(Class<T>, String) of type Enum<E> is not
applicable for the arguments (Class<capture#5-of ?>, String). The inferred type capture#5-of ? is not
a valid substitute for the bounded parameter <T extends Enum<T>>
还有这个:
static private Enum<?> getEnum(String enumFullName) {
...
Class<Enum<?>> cl = (Class<Enum<?>>)Class.forName(enumClassName);
// 1
return Enum.valueOf(cl, enumName);
// 2
Type safety: Unchecked cast from Class<capture#3-of ?> to Class<Enum<?>>
Bound mismatch: The generic method valueOf(Class<T>, String) of type Enum<E> is not applicable for the arguments (Class<Enum<?>>, String). The inferred type Enum<?> is not a valid substitute for the bounded parameter <T extends Enum<T>>
对于#1,除了,没有其他解决方案SuppressWarnings("unchecked")
。
对于#2,声明存在问题:
static private <E extends Enum<E>> E getEnum(String enumFullName)
您可以返回E
,但是编译器无法确定E
。没有类型E
或Class<E>
其他任何参数,这将允许它。您可以编写它,但是在某处会有未经检查的演员表,当您调用它时,可能会收到ClassCastException
。所以不要这样做。
只需将其更改为
static private Enum<?> getEnum(String enumFullName)
因为这样做会更有效。您会在每个呼叫站点收到警告,这是正确的,因为有一些警告需要警告。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句