JDK-8280745 : Allow SuppressWarnings to be used in package declarations
  • Type: CSR
  • Component: core-libs
  • Sub-Component: java.lang
  • Priority: P3
  • Status: Draft
  • Resolution: Unresolved
  • Fix Versions: 19
  • Submitted: 2022-01-26
  • Updated: 2022-01-26
Related Reports
CSR :  
Description
Summary
-------

Allow `SuppressWarnings` annotation to be used in package declarations.

Problem
-------
While allowed to be used on type and module declarations, among other targets, `SuppressWarnings` annotations cannot be used on package declarations.

Solution
--------

Include `PACKAGE` in the set of declared targets for `SuppressWarnings`.

Note: while the SuppressWarnings annotation does have a JLS section (9.6.4.5. @SuppressWarnings), the section doesn't mention the target list therefore doesn't appear to need to be updated.

Specification
-------------

    diff --git a/src/java.base/share/classes/java/lang/SuppressWarnings.java b/src/java.base/share/classes/java/lang/SuppressWarnings.java
    index 09ab6c4724b..726d67deece 100644
    --- a/src/java.base/share/classes/java/lang/SuppressWarnings.java
    +++ b/src/java.base/share/classes/java/lang/SuppressWarnings.java
    @@ -38,6 +38,9 @@ import static java.lang.annotation.ElementType.*;
      * However, note that if a warning is suppressed in a {@code
      * module-info} file, the suppression applies to elements within the
      * file and <em>not</em> to types contained within the module.
    + * Likewise, if a warning is suppressed in a {@code
    + * package-info} file, the suppression applies to elements within the
    + * file and <em>not</em> to types contained within the package.
      *
      * <p>As a matter of style, programmers should always use this annotation
      * on the most deeply nested element where it is effective.  If you want to
    @@ -52,7 +55,7 @@ import static java.lang.annotation.ElementType.*;
      * @jls 5.5 Casting Contexts
      * @jls 9.6.4.5 @SuppressWarnings
      */
    -@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, MODULE})
    +@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, PACKAGE, MODULE})
     @Retention(RetentionPolicy.SOURCE)
     public @interface SuppressWarnings {
         /**


Comments
Concretely, if the Target meta-annotation were removed from SuppressedWarnings it would be applicable in three new locations: * packages * record components * type parameters
26-01-2022

After some churn in earlier releases, Java 17 streamlined the rule for the applicability of an annotation interface without an @Target meta-annotation: all declaration contexts and no type contexts. (Note that record components prompted a new declaration context in Java 16.) I think there is some merit in letting SuppressWarnings have this wide, future-proof applicability rather than updating an explicit @Target every time.
26-01-2022