在泛型中添加@SuppressWarnings(“unchecked”)到单行会生成eclipse编译器错误

发布于 2024-12-04 06:53:04 字数 840 浏览 0 评论 0原文

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

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

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

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

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.

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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我还不会笑 2024-12-11 06:53:04

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

不过,您可以在局部变量声明上添加注释。

因此,编译器在这里尝试执行的是将 returnValue 解释为一种类型(因为这是唯一可以遵循方法体内注释的内容),但会失败。

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

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

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

You can however have annotations on local variable declarations.

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

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

@SuppressWarnings("unchecked")
T string = (T) collection.getString(attrName);
returnValue = string;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文