Simple Java Tip: Checked Type Casting

This is quite a trivial trick but it is very useful at times and I do not remember seeing it in any of the game related code sample I have read so far, so here it is.
Sometimes you get an object from somewhere and you know what type it should be and what to do if it’s not of that type (and by the way, if this is a common occurrence in your code it may be a hint that you should review your OO design). The usual java idiom to handle the situation is something like this:

if (o instanceof Something) {
s = (Something) o;
} else {
s = null;
}

Simple enough but if you have to do it a lot becomes kind of annoying. Here is a solution:

public class Cast {
public static T as(Class type, Object o) {
if (type.isInstance(o))
return type.cast(o);
return null;
}
}


And you can now write:

Something s = Cast.as(Something.class, o);
if(s != null) {
...
}

Bonus: if you’re getting objects from a heterogeneous map, create a simple delegating map wrapper that adds a casting get operation. I use this fairly frequently in my game code where entities have heterogeneous maps to hold their properties.

public class CastingMap implements Map {
private final Map m;

public CastingMap(Map m) {
this.m = m;
}

public T get(Class type, K key) {
return Cast.as(type, get(key));
}
...

Leave a Reply

Your email address will not be published. Required fields are marked *