This discussion is archived
2 Replies Latest reply: Dec 9, 2009 11:00 PM by 843793 RSS

@SuppressWarnings annotation causing compiler error

843793 Newbie
Currently Being Moderated
Anyone know why it is illegal to put a @SuppressWarnings annotation as shown in this example? I know this is a retarded example, and that you could just place the annotation on the method instead of inline with the code, so I am not looking for alternatives. I am just curious why it is illegal in the place shown.
public class SuppressTest {

     public void addFoo(Object bar) {
          List list = (List<String>) bar;
          @SuppressWarnings("unchecked")
          list.add("foo");
     }
}
  • 1. Re: @SuppressWarnings annotation causing compiler error
    796085 Newbie
    Currently Being Moderated
    Yes. Take a look at the definition of the SuppressWarnings annotation and you'll see all the valid places it can be used. Arbitrary statements isn't one of them (unfortunately).
  • 2. Re: @SuppressWarnings annotation causing compiler error
    843793 Newbie
    Currently Being Moderated
    Here is the correct way, to solve this problem. Maybe this makes clear, why the other way is not supported. The @SuppressWarnings affects only the definition of list.

    Anyway - you should be sure, that the cast, that is suppressed, is correct. And you cannot assure it in this special case, because everyone could call addFoo with nearly everything as parameter.
    public class SuppressTest {
        public void addFoo(Object bar) {
         @SuppressWarnings("unchecked")
         List<String> list = (List<String>) bar;
         
         list.add("foo");
        }
    }
    Edited by: yawah on 10.12.2009 07:58