The @SuppressWarnings annotation type allows Java programmers to disable compilation warnings for a certain part of a program (type, field, method, parameter, constructor, and local variable). Normally warnings are good. However in some cases they would be inappropriate and annoying. So programmers can choose to tell the compiler ignoring such warnings if needed.
This annotation type must be used with one or more warnings as its arguments, for example:
@SuppressWarnings("unchecked") @SuppressWarnings({"unchecked", "deprecation"})
List of warnings vary among Java compilers. The Java Language Specification mentions only “unchecked” warning (section 9.6.3.5). To see the list of warnings which would be issued by the Oracle’s Java compiler, type the following command:
javac -X
We’ll see the complete list of warnings after the line starts with -Xlint:{, as shown in the following screenshot:
So the warnings issued by Oracle’s Java compiler (as of Java 1.7) are: all, cast, classfile, deprecation, dep-ann, divzero, empty, fallthrough, finally, options, overrides, path, processing, rawtypes, serial, static, try, unchecked, varargs.
Different IDEs provide different list of warnings issued by their own compilers, e.g. list of suppress warnings provided by Eclipse IDE’s Java compiler.
Here are some of the most commonly used warnings which have same meaning across compilers: all, deprecation, unchecked.
@SuppressWarnings("unchecked") void uncheckedGenerics() { List words = new ArrayList(); words.add("hello"); // this causes unchecked warning }
If the above code is compiled without @SuppressWarnings("unchecked")annotation, the compiler will complain like this:
XYZ.java uses unchecked or unsafe operations.
@SuppressWarnings("deprecation") public void showDialog() { JDialog dialog = new JDialog(); dialog.show(); // this is a deprecated method }
XYZ.java uses or overrides a deprecated API.
Suppress all unchecked and deprecation warnings for all code inside the Foo class below:
@SuppressWarnings({"unchecked", "deprecation"}) class Foo { // code that may issue unchecked and deprecation warnings }
void foo(List inputList) { @SuppressWarnings("unchecked") List<String> list = (List<String>) inputList; // unsafe cast }
Other Annotations in Core Java: