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 [Bloch 2008]. It is permissible to use the @SuppressWarnings("unchecked")
annotation to suppress unchecked warnings if, and only if, 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 MSC00-J. Do not mix generic with non-generic raw types in new code.
According to the Java API [API 2006], Annotation Type SuppressWarnings
documentation
...
The @SuppressWarnings
annotation can be used in the declaration of variables and methods, methods as well as an entire class. It is, however, very important to narrow down its scope so that other noteworthy warnings within the same scope are not silently ignored.
...
In this noncompliant code example, the @SuppressWarnings
annotation's scope encompasses the whole class. This is dangerous as because all unchecked warnings within the class will be suppressed. Oversights of this nature can lead to a ClassCastException
at runtime.
...
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. As Because the return
statement is not a declaration, the Java Language Specification [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 . [Bloch 2008].
Code Block | ||
---|---|---|
| ||
@SuppressWarnings("unchecked") public <T> T[] toArray(T[] a) { if (a.length < size) return (T[]) Arrays.copyOf(elements, size, a.getClass()); // Produces unchecked warning // ... } |
...
When it is impossible to use the @SuppressWarnings
annotation, such as in the case of the preceding noncompliant code example, declare a new variable to hold the return value and adorn it with the @SuppressWarnings
annotation.
...
This guideline cannot be statically enforced in full generality; static analysis may could be possible for some interesting special cases.
...