Search code examples
javacastingwarningssuppress-warningsunchecked

SuppressWarnings annotation when assigning to instance variable


A library I'm using (and can't change) has a raw Map being returned to me, so I want to suppress the warning about an unchecked cast. It seems that it isn't working when I try it on an instance variable though.

I've enumerated the cases below, and for brevity, combined them into a single code example, even though I tested them individually.

class Foo {
  @SuppressWarnings("unchecked") //doesn't work
  private Map<String, String> map;

  @SuppressWarnings("unchecked") //works
  private void doSomething() {
    @SuppressWarnings("unchecked") //syntax error
    this.map = Library.getMap();
  }
}

What is the most specific spot that I can suppress the warning? I would prefer to not do it on the entire method, but that is the only spot where it currently works for me.


Solution

  • You expected to suppress warning when there's an issue, the issue is inside doSomething in line

    this.map = Library.getMap();
    

    You can't suppress the assignment itself, so you need to go to the outer scope which is the method or the class

    As a matter of style, programmers should always use this annotation on the most deeply nested element where it is effective. If you want to suppress a warning in a particular method, you should annotate that method rather than its class.

    If you assignment would be in initialization, you could suppress it:

    @SuppressWarnings("unchecked" )
    private Map<String, String> map = Library.getMap();