在泛型中将@SuppressWarnings(“unchecked”)添加到单行会生成eclipse编译器错误 [英] Add @SuppressWarnings("unchecked") in generics to single line generates eclipse compiler error

查看:1609
本文介绍了在泛型中将@SuppressWarnings(“unchecked”)添加到单行会生成eclipse编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我必须为一个泛型投入一个String,并产生一个警告。

 类型安全性:未检查从String转换为T 




  • 如果我在方法声明上面添加 @SuppressWarnings(unchecked)


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

    b $ b


这很好。

  @SuppressWarnings未选中)
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)//编译器错误:returnValue无法解析为类型
returnValue = T)collection.getString(attrName);
}

任何想法是什么导致两种抑制警告的方法之间的差异? / p>

解决方案

您不能对任意表达式进行注释(可能以后会添加)。



您可以在本地变量声明上有注释。尝试在这里做的是将 returnValue 解释为一个类型(因为这是唯一可以跟随注释在方法体内)并失败。



returnValue 声明中添加注释在此情况下无效。然而,您可以创建一个新的局部变量,在初始化器中执行转换并注释。

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


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?

解决方案

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;

这篇关于在泛型中将@SuppressWarnings(“unchecked”)添加到单行会生成eclipse编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆