Java – Why Can’t I SuppressWarnings on a Package

annotationsjava

I see from the javadoc that the @SuppressWarnings annotation applies to

TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE

targets. Why does it not also apply to PACKAGE?

I have some generated code which contains some raw types warnings. I'd like to be able to add a package-info.java file for the generated classes (in a separate physical directory but the same java package) which tells eclipse to ignore any raw types warnings emanating from the generated classes in package.

Why is this not supported? Is there an alternate way of suppressing a warning in an entire package?

Best Answer

The reason that suppressing warnings at the package level is not allowed was explained in the response to an old bug report (Status - Closed, Will Not Fix): Allow SuppressWarnings to be specified at the package level.

The warnings actually indicates potential problems in the generated code.

Currently, SuppressWarnings have the desirable property of only affecting lexically nested code. This means that you can immediately see if a warning might be suppressed in code you're reading.

This proposal would violate this property to solve an uncommon problem which in most cases can be worked around.

There are a couple of work arounds suggested in that response as well.

  1. compile the generated code by itself using -source 1.4 and -target 5.

  2. request an updated version of javacc which either uses suppresswarnings or doesn't generate code which causes warnings.

I think the first suggestion, putting the generated code in its own project, should work for you. The second suggestion looks like its more specific to the problem in the bug report. I don't know if you're using javacc or not.