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

徘徊边缘 提交于 2019-12-10 00:36:49

问题


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?


回答1:


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;


来源:https://stackoverflow.com/questions/7387749/add-suppresswarningsunchecked-in-generics-to-single-line-generates-eclipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!