在泛型中添加@SuppressWarnings(“unchecked”)到单行会生成eclipse编译器错误
我偶然发现了一种我不理解的奇怪行为。
我必须将字符串转换为泛型,它会产生警告。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能对任意表达式进行注释(还吗?也许他们稍后会添加它)。
不过,您可以在局部变量声明上添加注释。
因此,编译器在这里尝试执行的是将
returnValue
解释为一种类型(因为这是唯一可以遵循方法体内注释的内容),但会失败。在这种情况下,将注释放在
returnValue
的声明处并没有帮助。但是,您可以创建一个新的局部变量,在初始化程序中执行强制转换并对其进行注释。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.