Search |
||
Getting rid of unchecked warnings for castsPosted by emcmanus on March 30, 2007 at 3:27 AM PDT
If you've ever made a serious effort to get rid of "unchecked" warnings from the Java compiler (the ones it gives you with -Xlint:unchecked) then you'll probably have found some cases where you know a cast is correct but you can't convince the compiler of it. Is there anything better than adding @SuppressWarnings("unchecked") around the whole method? The problem with the @SuppressWarnings solution is that it's much too broad. It suppresses warnings for the whole method, even though it's just one little cast that you want to allow. What if there's another place in the method where the compiler would have given a warning, telling you about a real problem? There's also a readability problem. If it's a big method, it can be hard to work out which particular line is the reason for the @SuppressWarnings annotation; you have to add a comment saying "yoo-hoo! I'm the reason!" Fortunately, there's a good solution. Suppose your code does this:
List<String> list = (List<String>) x;
You can change it to this:
List<String> list = cast(x);
where the
@SuppressWarnings("unchecked")
private static <T> T cast(Object x) {
return (T) x;
}
If there several different classes where you need this method, you could make it public and put it in a utility class, say Util.java. Then every class that needs it can use The magic here is that the compiler can use
type inference to figure out what The compiler can do this if you're assigning the result of In some cases even this won't work. For example, if you want to use the
<E> Set<E> result(Object x) {
E e = cast(x); // does not compile
return Collections.singleton(e);
}
You can work around this using the little-known syntax for "explicit type parameters":
<E> Set<E> result(Object x) {
E e = Util.<E>cast(x);
return Collections.singleton(e);
}
This is ugly, notably because you can't write just This (By the way I'm sure this »
Related Topics >>
Programming Comments
Comments are listed in date ascending order (oldest first)
|
||
|
|
The cast() method vulnerabilities