如何重写以下方法而不出现未经检查的警告?
private <K> Map<K, Object> createMap(final Class<K> keyClass) {
final boolean isEnum = keyClass.isEnum();
if(isEnum) {
// The following two lines throw warnings
final Class<? extends Enum<?>> enumCls = (Class<? extends Enum<?>>)keyClass;
final Map<K, Object> map = (Map<K, Object>)new EnumMap(enumCls);
return map;
}
else{
final Map<K, Object> map = new HashMap<K, Object>();
return map;
}
}
警告
found : java.lang.Class<K>
required: java.lang.Class<? extends java.lang.Enum<?>>
final Class<? extends Enum<?>> enumCls = (Class<? extends Enum<?>>)keyClass;
^
T.java:9: warning: [unchecked] unchecked call to EnumMap(java.lang.Class<K>) as a member of the raw type java.util.EnumMap
final Map<K, Object> map = (Map<K, Object>)new EnumMap(enumCls);
^
T.java:9: warning: [unchecked] unchecked cast
found : java.util.EnumMap
required: java.util.Map<K,java.lang.Object>
final Map<K, Object> map = (Map<K, Object>)new EnumMap(enumCls);
^
3 warnings
private <K> Map<K, Object> createMap(final Class<K> keyClass) {
final boolean isEnum = keyClass.isEnum();
if(isEnum) {
// The following two lines throw warnings
final Class<? extends Enum<?>> enumCls = (Class<? extends Enum<?>>)keyClass;
final Map<K, Object> map = (Map<K, Object>)new EnumMap(enumCls);
return map;
}
else{
final Map<K, Object> map = new HashMap<K, Object>();
return map;
}
}
Warnings
found : java.lang.Class<K>
required: java.lang.Class<? extends java.lang.Enum<?>>
final Class<? extends Enum<?>> enumCls = (Class<? extends Enum<?>>)keyClass;
^
T.java:9: warning: [unchecked] unchecked call to EnumMap(java.lang.Class<K>) as a member of the raw type java.util.EnumMap
final Map<K, Object> map = (Map<K, Object>)new EnumMap(enumCls);
^
T.java:9: warning: [unchecked] unchecked cast
found : java.util.EnumMap
required: java.util.Map<K,java.lang.Object>
final Map<K, Object> map = (Map<K, Object>)new EnumMap(enumCls);
^
3 warnings
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编译器无法执行某些检查,并且会向您发出警告。在此方法中避免这些问题的唯一方法是在方法之前添加注释,
即使是像 ArrayList 这样的集合,也不会在没有警告的情况下编译。
There are some checks the compiler cannot do and it will give you a warning. The only way to avoid these in this method is to add annotation before the method
Even the collections like ArrayList so not compile without warnings.
您应该使用“instanceof”来检查类型,编译器知道该检查,并且如果您这样做,则不会在第一行发出警告。
第二行应该写成“new EnumMap(enumCls);”。
You should use "instanceof" to check type, the compiler is aware of that check and won't throw a warning on the first line if you do that.
The second line should be written like "new EnumMap<K, Object>(enumCls);".
好吧,至少有一种方法可以获取
Class>
without warning:尽管如此,正如已经说过的,无法使用
K
作为 EnumMap 的类型参数。因此(在评估风险之后)抑制警告是完全可以的。Well, there is at least a way to get the
Class<? extends Enum<?>>
without warning:Still, as has already been said, there is no way to use
K
as type parameter for EnumMap. Hence suppressing the warning (after evaluating the risks) is perfectly fine.