SuppressWarnings

3

Update: An updated and enhanced version of this info now exists here.


One of the new built-in annotations in Java 5 is SuppressWarnings. You can use this annotation on all the available annotation levels (class, field, method, constructor, local variable, etc) to suppress warnings that might be generated by a compiler.

I typically use Eclipse and they provide the ability to “quick fix” a warning in some cases by adding a SuppressWarnings annotation, which looks something like this:
@SuppressWarnings("deprecation") and is placed before a method, field, class, etc. In this case, this annotation suppresses a deprecated access warning. You can put multiple values in there as well with an annotation like @SuppressWarnings({"unchecked", "deprecation"}).

I found need to use this recently on some 3rd-party generated code. Instead of needing to fix the modified code after every generation I was able to just add @SuppressWarnings("all") to the generated class and make my troubles go away. :) Well, at least to the extent that I cared about in this instance. In general, I’m a big fan of a shared set of compiler defaults and a no-warning policy, but generated code can be something of an exception.

One gotcha is that because warning messages are compiler-dependent, there is not a lot of information out there about what values are allowed. The language spec talks only about unchecked and deprecation as values. The Sun JDK has seven categories (as documented here): all, deprecation, unchecked, fallthrough, path, serial, and finally.

I did some more hunting and found a list of the allowed values in the Eclipse compiler (scroll to the very bottom), which adds quite a bit to the Sun categories. Couldn’t find much from other JVMs.

Comments

3 Responses to “SuppressWarnings”
  1. toby says:

    Brilliant summary, thanks. Helped me get rid of a lot of annoying warnings in eclipse. And thanks for pointing out the quick fix solution too, I hadn’t noticed that option.

  2. Antero Laukkanen says:

    yeah.. thanks a lot. helped me too with eclipse, I got my single warning disappear for a utility method that is not always used..

  3. Burt says:

    Thanks, Alex, this certainly helped me understand how to handle warnings from something like

    ArrayList al = (ArrayList)obj;