Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The compiler issues unchecked warnings when it detects potential type safety issues arising from mixing raw types with generic code. This includes unchecked cast warnings, unchecked method invocation warnings, unchecked generic array creation warnings, and unchecked conversion warnings [java:Bloch 2008]. It is permissible to use the @SuppressWarnings("unchecked") annotation to suppress unchecked warnings when, and only when, the warning emitting code is guaranteed to be typesafe. A common usecase is mixing legacy code with new client code. The perils of ignoring unchecked warnings are discussed extensively in guideline rule OBJ10-J. Do not mix generic with non-generic raw types in new code.

According to the Java API [java:API 2006], Annotation Type SuppressWarnings documentation

...

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 [java:JLS 2005] 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 [java: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
 // ...
}

...

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MSC07-J

medium

probable

high

P4

L3

Automated Detection

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

...

Search for vulnerabilities resulting from the violation of this guideline rule on the CERT website.

Bibliography

[java:Bloch 2008] Item 24: "Eliminate unchecked warnings"

...