...
Noncompliant Code Example
In this noncompliant code example, the @SuppressWarnings
annotation's scope encompasses the whole class. This is dangerous as all unchecked warnings within the class will be suppressed. Oversights of this nature can lead to a ClassCastException
at runtime.
Code Block |
---|
|
@SuppressWarnings("unchecked") class Legacy {
Set s = new HashSet();
public final void doLogic(int a,char c) {
s.add(a);
s.add(c); // typeType unsafe operation, ignored
}
}
|
...
Code Block |
---|
|
class Legacy {
@SuppressWarnings("unchecked") Set s = new HashSet();
public final void doLogic(int a,char c) {
s.add(a); //produces Produces unchecked warning
s.add(c); // producesProduces unchecked warning
}
}
|
Noncompliant Code Example
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 the return
statement is not a declaration, the Java Language Specification [JLS 05] 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 08]
Code Block |
---|
|
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
if (a.length < size)
return (T[]) Arrays.copyOf(elements, size, a.getClass()); // producesProduces 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 @SuppressWarings
@SuppressWarnings
annotation.
Code Block |
---|
|
// ...
@SuppressWarnings("unchecked") T[] result =
(T[]) Arrays.copyOf(elements, size, a.getClass());
return result;
// ...
|
...