...
Limit the scope of the @SuppressWarnings
annotation to the nearest unchecked warning-generating codecode that generates a warning. In this case, it may be used in the declaration for the Set
.
Code Block | ||
---|---|---|
| ||
class Legacy { @SuppressWarnings("unchecked") Set s = new HashSet(); public final void doLogic(int a,char c) { s.add(a); // Produces unchecked warning s.add(c); // Produces unchecked warning } } |
Noncompliant Code Example (ArrayList
)
This noncompliant code example is from the implementation of java.util.ArrayList
.
...
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 (ArrayList
)
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.
...