As you know when it comes to casting a la Java 1.4 a developer will have to write, typically, something like this:
Object a = "iron man"; String b = (String)a;
Well, there is nothing wrong with this code. However, it is not pretty :). With Java 5.0 the casting mechanism is more explicit and nicer. The best thing of it is that it does not throw warnings, which it is a big deal :)
Object a = "iron man"; String b = String.class.cast(a);
Not that bad, huh? Hmm, well…Okay, Okay, you got me. This still does not look that pretty and it is more verbose than the (Object)a style. How can I make it prettier? the ans: Generics
public static <T, E extends T> E cast(T me, Class<? extends E> to){
return to.cast(me);
}
....
Object a = "iron man";
String b = cast(a, String.class);
Believe it or not, I love this technique. It works like a charm with objects that are part of the same inheritance chain. I know this method requires more tweaking to make it suitable for handling the casting of collections. But hey! this is just a working idea!