@SuppressWarnings on variable declarations
permalinkI’ve been using this trick for a while and I thought I’d share it. For those who live by Eclipse’s quickfixes, it’s not entirely obvious that it’s legal.
If you have legacy code like the code below, where foo.list() is a Java 1.4-compatible method returning java.util.List, you’ll normally see an “unchecked cast” warning on the assignment like so:
public void doSomeListStuff(Foo foo) {
List list = foo.list(); // Warning: unchecked cast
for (Blah blah : list) {
frobinate(blah);
}
}
Normally, Eclipse offers to fix it for you like this:
@SuppressWarnings("unchecked")
public void doSomeListStuff(Foo foo) {
List list = foo.list(); // Everything is A-OK!
for (Blah blah : list) {
frobinate(blah);
}
}
A better solution takes advantage of Java’s less-touted ability to annotate local variable declarations. By annotating the declaration and assignment instead of the method, the warning suppression is limited in scope to the assignment expression itself:
public void doSomeListStuff(Foo foo) {
@SuppressWarnings("unchecked")
List list = foo.list();
for (Blah blah : list) {
frobinate(blah);
}
}
This keeps your code under maximum protection of Java’s generic strong typing. By annotating a whole method with @SuppressWarnings(“unchecked”), you may inadvertently introduce a later, unsafe cast that could cause a bug down the line.
Read full post