Thursday, February 23, 2012

Java generics, collections and reflection


Generics are a facility of generic programming that was added to Java in J2SE 5.0. It allows a method to operate on objects of various types while providing compile-time safety. A common use of this feature is when using a java.util.Collection that can hold objects of any type, to specify the specific type of object stored in it.

Generics is one of the new features in the Java language I really like. It makes working with collections easier and the compile-time checking reduces the risk of run time errors.
Lately I have been playing around with a legacy dependency injection system relying on reflection to inject properties into objects. This was when I discovered one of the drawbacks with generics: Reflection and generics are not the best match
This is for instance the code needed for retrieving the generic type of a method returning a generified java.util.Collection
Class<?> getGenericType(final Method pMethod) {
  Type[] genericTypes = pMethod.getGenericParameterTypes();
  if (genericTypes.length == 0) {
    throw new IllegalArgumentException("Method has no generic parameters");
  }
  Type genericType = genericTypes[0];
  Class<?> propertyType = Object.class;
  if (theType instanceof ParameterizedType) {
    ParameterizedType parameterizedType = (ParameterizedType)genericType;
    propertyType = (Class<?>) parameterizedType.getActualTypeArguments()[0];
  }
  return genericType;
}
As you can see it’s not the prettiest code in the world, but luckily it works.

1 comment:

  1. http://www.scribd.com/doc/163398138/Java-Reflection-with-Generics-Practical-Case

    ReplyDelete