Class.cast(..) and Generics - a powerful combination

July 12th, 2008

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!

programming, random ideas | Comments | Trackback

Leave a Reply

  1.  
  2.  
  3.  
  4. XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
  5. Spam Protection by WP-SpamFree

You can keep track of new comments to this post with the comments feed.

 

July 2008
M T W T F S S
« Jun   Oct »
 123456
78910111213
14151617181920
21222324252627
28293031  

Categories

Archives

Tags