java - 将泛型中的 @SuppressWarnings ("unchecked") 添加到单行会生成 Eclipse 编译器错误

标签 java eclipse generics compiler-errors suppress-warnings

我偶然发现了一种我不理解的奇怪行为。

我必须将字符串转换为泛型,它会产生警告。

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 解释为一种类型(因为这是唯一可以跟随方法体内注解的东西)并且失败了.

将注释放在 returnValuedeclaration 处在这种情况下没有帮助。但是,您可以创建一个新的局部变量,在初始化程序中执行强制转换并对其进行注释。

@SuppressWarnings("unchecked")
T string = (T) collection.getString(attrName);
returnValue = string;

关于java - 将泛型中的 @SuppressWarnings ("unchecked") 添加到单行会生成 Eclipse 编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7387749/

相关文章:

c# - 必须做什么才能将引用类型的值用作字典键?

java - 没有额外空间的 O(n) 中的反转堆栈不会发生

java - Manifest.mf 文件查看器?

java - 类似OSGI/Eclipse扩展点的Spring机制

Eclipse 在不使用箭头键的情况下向左/向右/向上/向下移动光标

java - Eclipse RCP 应用程序 - 如何检测应用程序何时空闲?

Java 泛型 - 通配符

C# 错误 CS1061 : Type `System.Collections.Generic.List<int>' does not contain a definition for `Length'

Linux 上的 JavaFX 显示 "Graphics Device initialization failed for : es2, sw"

java - 在启动另一个函数的同时在后台运行一个函数