Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: reordered some text around NCE/CS

...

In this noncompliant code example, the @SuppressWarnings annotation's scope encompasses the whole class. This is dangerous because all unchecked warnings within the class will be suppressed. Oversights of this nature can lead to a ClassCastException at runtime. 

Code Block
bgColor#FFCCCC
@SuppressWarnings("unchecked") class Legacy {
  Set s = new HashSet();
  public final void doLogic(int a, char c) {
    s.add(a);
    s.add(c); // Type unsafe operation, ignored
  }
}

This is dangerous because all unchecked warnings within the class will be suppressed. Oversights of this nature can lead to a ClassCastException at runtime.

Compliant Solution

Limit the scope of the @SuppressWarnings annotation to the nearest unchecked warning-generating code. In this case, it may be used in the declaration for the Set.

...

This noncompliant code example is from the implementation of java.util.ArrayList. When the class is compiled, it emits an unchecked cast warning, as shown. Because the return statement is not a declaration, the Java Language Specification [JLS 2011] makes it impossible to suppress the warning trivially. Consequently, the @SuppressWarnings is used over method scope. This can cause issues when some functionality that performs type-unsafe operations is added to the method at a later date [Bloch 2008]. 

Code Block
bgColor#FFCCCC
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
  if (a.length < size)
    return (T[]) Arrays.copyOf(elements, size, a.getClass()); // Produces unchecked warning
 // ...
}

When the class is compiled, it emits an unchecked cast warning.

Code Block
// Unchecked cast warning
ArrayList.java:305: warning: [unchecked] unchecked cast found : Object[], required: T[]
return (T[]) Arrays.copyOf(elements, size, a.getClass());

Because the return statement is not a declaration, the Java Language Specification [JLS 2011] makes it impossible to suppress the warning trivially by using @SuppressWarnings at that statement. Consequently, the @SuppressWarnings is used over method scope where it is allowed. This can cause issues when some functionality that performs type-unsafe operations is added to the method at a later date [Bloch 2008].

Compliant Solution

When it is impossible to use the @SuppressWarnings annotation, as in the preceding noncompliant code example, declare a new variable to hold the return value and adorn it with the @SuppressWarnings annotation.

...

This rule cannot be statically enforced in full generality; static analysis could be possible for some interesting special cases.

Bibliography

...