我偶然发现了一种我不理解的奇怪行为。
我必须将字符串转换为泛型,它会产生警告。
Type safety : Unchecked cast from String to T
如果我在方法声明上方添加
@SuppressWarnings("unchecked")
它工作正常。如果我将它添加到赋值之上,它会在 eclipse 。
这很好用。
@SuppressWarnings("unchecked")
public <T> T search(final String query){
T returnValue = null;
...
if(returnValue instanceof String){
returnValue = (T) collection.getString(attrName);
}
这不能正常工作。
public <T> T search(final String query){
T returnValue = null;
...
if(returnValue instanceof String){
@SuppressWarnings("unchecked") // Compiler error: "returnValue cannot be resolved to a type"
returnValue = (T) collection.getString(attrName);
}
知道是什么导致了两种抑制警告的方法之间的差异吗?
最佳答案
您不能在任意表达式上添加注释(但是?也许他们稍后会添加它)。
您可以在局部变量声明上添加注释。
所以编译器尝试在这里要做的就是将 returnValue
解释为一种类型(因为这是唯一可以跟随方法体内注解的东西)并且失败了.
将注释放在 returnValue
的 declaration 处在这种情况下没有帮助。但是,您可以创建一个新的局部变量,在初始化程序中执行强制转换并对其进行注释。
@SuppressWarnings("unchecked")
T string = (T) collection.getString(attrName);
returnValue = string;
关于java - 将泛型中的 @SuppressWarnings ("unchecked") 添加到单行会生成 Eclipse 编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7387749/