Richer Java runtime type info with javaRuntype

By now you surely know that Java's generics info is erased from objects during compilation. For example, given an object whose runtime class is java.util.List, I cannot tell at runtime whether the object was originally a List<Integer>, or a List<String>, or what have you.

However, Java has some generics capability using reflection. There are generics-aware counterparts to the generics-unaware reflection capabilities that Java has had for so long. Given a method or constructor, you can discover the types of its parameters. Given a method, you can discover its return type. Given a field, you can discover its type. Given a class or interface, you can discover its superclass, implemented interfaces, or superinterfaces.

The generics-aware reflection capabilities deal not in java.lang.Class objects, but in instances of java.lang.reflect.Type. Type by itself is not terribly useful: it prescribes no methods! To do meaningful work with Types, you have to test whether they're instances of either Class, ParameterizedType, WildcardType, GenericArrayType, or TypeVariable, and downcast. Worse still, if your Type is not a Class, you miss out on nice things you can ask Classes, such as isAssignableFrom().

Not a big deal, perhaps, until you work on a library or extension that could put the generics info to good use.

Enter javaRuntype. This fantastic library does the dirty work of providing Class-like functionality such as isAssignableFrom() for you. Kudos to Daniel Fernandez for his attempt to rescue java.lang.reflect.Type and its brethren from second-class citizen status.

Written on March 8, 2011