Cast away with Java generics

They say it’s those little things in life. I believe the same is very much true for your code as well. Here’s an example with casting and generics in Java.

After a long hard day in the code editor I often find that what makes me happy about my day, and the work I check in to our SCM, is not always the additions to an advanced algorithm, or an insanely compact chunk of awesomeness, but it’s more often a small piece of beautiful code. One of the ugliest lines of code I see in Java, are lines involved with casting.

I recently started doing a bit of coding on a web application a couple of weeks back. Suddenly I found myself writing a lot of casting statements when fetching data from session, which made my code want to crawl out of the editor due to it’s own ugliness. Here is an example:

Session webappSession = ...

Map<String, Map<String, Collection<Entity>>> myUglyMap = (Map<String, Map<String, Collection<Entity>>>)(webappSession.getAttribute("myUglyMap"));

Oh boy! I figured there must be some other way to write this. With our static imports fever as of late I came up with a tiny piece of code which made me go home smiling that day. That little thing which made it all so much more beautiful…

public static <T> T cast(Object o) {

    return (T) o;

}

Placed in a easily accessible class in your favourite toolbox project, the messy snippet above quickly becomes much better:

import static com.mydomain.CastUtils.cast;

/* snipp */

Session webappSession = ...

Map<String, Map<String, Collection<Entity>>> beautiful = cast(webappSession.getAttribute("beautiful"));
A small piece of simple code, so full of awesomeness.

About the Author

I've been working as a lead developer at Integrasco AS since it's startup in 2004. My interests in software development are ranging from the lowest bit to design patterns and development methods. On a daily basis my main area of responsibility is data mining technology as well as a bit of team management. In addition to my work at Integrasco AS, I am also running an open source project called iTunes Agent over on Sourceforge, which provides non-iPod owners with a way to transfer music from iTunes to their media player.