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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7387749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 16:58:53  来源:igfitidea点击:

Add @SuppressWarnings("unchecked") in generics to single line generates eclipse compiler error

javaeclipsegenericscompiler-errorssuppress-warnings

提问by Farmor

I have stumbled upon a strange behavior that I don't understand.

我偶然发现了一种我不明白的奇怪行为。

I have to cast a String to a generic and it's producing a warning.

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

Type safety : Unchecked cast from String to T
  • If I add @SuppressWarnings("unchecked")above the method declaration it works fine.

  • If I add it above the assignment it produces a compiler error in eclipse.

  • 如果我@SuppressWarnings("unchecked")在方法声明上方添加它就可以正常工作。

  • 如果我将它添加到赋值之上,它会在 Eclipse 中产生编译器错误。

This works fine.

这工作正常。

@SuppressWarnings("unchecked")
public <T> T search(final String query){
 T returnValue = null;
 ...
 if(returnValue instanceof String){
  returnValue = (T) collection.getString(attrName);
 }

This don't work fine.

这行不通。

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);
 }

Any idea what's causing the discrepancy between the two methods of suppressing the warning?

知道是什么导致了两种抑制警告的方法之间的差异吗?

回答by Joachim Sauer

You can't have annotation on arbitrary expressions (yet? Maybe they'll add it later on).

您不能对任意表达式进行注释(但是?也许他们稍后会添加它)。

You canhowever have annotations on local variable declarations.

但是,您可以对局部变量声明进行注释。

So what the compiler triesto do here is to interpret returnValueas a type (as that's the only thing that can follow an annotation inside a method body) and fails.

所以编译器在这里试图做的是解释returnValue为一种类型(因为这是方法体中唯一可以跟在注解之后的东西)并且失败。

Putting the annotation at the declarationof returnValuedoes not help in this case. You can however create a new local variable where you perform the cast in the initializer and annotate that.

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

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