The compiler issues unchecked warnings when it When the compiler detects potential type-safety issues arising from mixing raw types with generic code. This includes , it issues unchecked warnings, including 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 when, and only when, the warning-emitting code is guaranteed to be type safe. A common use case is mixing legacy code with new client code. The perils of ignoring unchecked warnings are discussed extensively in OBJ03-J. Do not mix generic with nongeneric raw types in new code.
According to the Java API [API 2011], Annotation Type SuppressWarnings
documentation [API 2011],
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 suppress a warning in a particular method, you should annotate that method rather than its class.
...
In this noncompliant code example, the @SuppressWarnings
annotation's scope encompasses the whole class. :
Code Block | ||
---|---|---|
| ||
@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 code is dangerous 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
. :
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 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()); |
...
This rule cannot be statically enforced in full generality; static analysis could be possible for some special cases.
Bibliography
[Bloch 2008] | Item 24 |
...
, "Eliminate |
...
Unchecked Warnings" |
...