Notifications and Warnings

When an API is deprecated, developers must be notified. The deprecated API may cause problems in your code, or, if it is eventually removed, cause failures at run time.

The Java compiler generates warnings about deprecated APIs. There are options to generate more information about warnings, and you can also suppress deprecation warnings.

Compiler Deprecation Warnings

If the deprecation is forRemoval=false, the Java compiler generates an "ordinary deprecation warning". If the deprecation is forRemoval=true, the compiler generates a "removal warning".

The two kinds of warnings are controlled by separate -Xlint flags: -Xlint:deprecation and -Xlint:removal. The javac -Xlint:removal option is enabled by default, so removal warnings are shown.

The warnings can also be turned off independently (note the "–"): -Xlint:-deprecation and -Xlint:-removal.

This is an example of an ordinary deprecation warning.

$ javac src/example/DeprecationExample.java	
Note: src/example/DeprecationExample.java uses or overrides a deprecated API.	
Note: Recompile with -Xlint:deprecation for details.	

Use the javac -Xlint:deprecation option to see what API is deprecated.

$ javac -Xlint:deprecation src/example/DeprecationExample.java	
src/example/DeprecationExample.java:12: warning: [deprecation] getSelectedValues() in JList has been deprecated	
   Object[] values = jlist.getSelectedValues();	
                     ^	
1 warning	

Here is an example of a removal warning.

public class RemovalExample {
    public static void main(String[] args) {
        System.runFinalizersOnExit(true);
    }
}
$ javac RemovalExample.java
RemovalExample.java:3: warning: [removal] runFinalizersOnExit(boolean) in System 
has been deprecated and marked for removal
        System.runFinalizersOnExit(true);
              ^
1 warning
==========

Suppressing Deprecation Warnings

The javac -Xlint options control warnings for all files compiled in a particular run of javac. You may have identified specific locations in source code that generate warnings that you no longer want to see. You can use the @SuppressWarnings annotation to suppress warnings whenever that code is compiled. Place the @SuppressWarnings annotation at the declaration of the class, method, field, or local variable that uses a deprecated API.

The @SuppressWarnings options are:
  • @SuppressWarnings("deprecation") — Suppresses only the ordinary deprecation warnings.

  • @SuppressWarnings("removal") — Suppresses only the removal warnings.

  • @SuppressWarnings({"deprecation","removal"}) — Suppresses both types of warnings.

Here’s an example of suppressing a warning.

   @SuppressWarnings("deprecation")
   Object[] values = jlist.getSelectedValues();

With the @SuppressWarnings annotation, no warnings are issued for this line, even if warnings are enabled on the command line.