luc*_*uta 1 java generics compiler-errors
我有以下代码块:
final Map<String, Double> map;
if (cond) {
int currency = 44;
@SuppressWarnings("unchecked")
map = (Map<String, Double>)objectA.get();
}else {
map= ....}
Run Code Online (Sandbox Code Playgroud)
get()objectA返回raw的方法HashMap(我知道在那里使用泛型会很好,我的问题会解决,但我无法更改该类的代码).如果我删除 @SuppressWarnings("unchecked")线路,显然我会收到TypeSafety警告.但是当我在线下添加supress警告时,我得到以下错误:
map cannot be resoved to a type!
Run Code Online (Sandbox Code Playgroud)
有人能解释我为什么吗?
编译器认为这@SuppressWarnings("unchecked")是一个表达式,并且没有终端运算符;.但是,如果添加它,表达式无效.
您必须在变量定义之前注释方法或使用注释:
@SuppressWarnings("unchecked")
public void method() {
@SuppressWarnings("unchecked") final Map<String, Double> map;
if (cond) {
int currency = 44;
map = (Map<String, Double>)objectA.get();
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,javadoc表明:
作为一种风格问题,程序员应该始终在最有效的嵌套元素上使用此注释.