Pure Danger Tech



05 Jan 2007

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.