Saturday, January 05, 2008

Type-Inference with Generics

Generics in Java 5 and beyond offer many cool features, one of which is type-inference.

Consider this, for an example:

public Object load(Class objectClass, Serializable id);

This is an Object-Relational mapping method that loads an object from a repository based on the object id. Unfortunately, it requires you to cast the object after the method call, cluttering your code unnecessarily, as shown in this example:

Person person = (Person)mapper.load(Person.class, 35);

While Java Generics are often applied at the Class level, they can also be applied at the method level. In fact, in this case, they would offer a neat application of type-inference. Here is how the load method is rewritten to take advantage of that:

public <TYPE> Object load(Class<TYPE> objectClass, Serializable id);

Now, one way of calling this method is as follows:

Person person = mapper.<Person>load(Person.class, 35);

Of course, this does not get rid fo the clutter, yet only moves it by turning the cast into a generic <TYPE> specification.

However, there is another way to call the method that takes advantage of type-inference. Java can figure out the TYPE from the objectClass you pass to the method, so all you need to do is this:

Person person = mapper.load(Person.class, 35);

This achieves clean loading of the object without any necessity to repeat yourself and specify the Person class again in a cast or generic <TYPE> specification.

No comments: