Monday, June 18, 2012

New in Guava 12: TypeToken, a better Class or TypeLiteral

I'm slow to read up on the Guava 12 release — it came out in April.

Among the changes is this gem: TypeToken.

Guava provides TypeToken, which uses reflection-based tricks to allow you to manipulate and query generic types, even at runtime. Think of a TypeToken as a way of creating, manipulating, and querying Type (and, implicitly Class) objects in a way that respects generics.

Note to Guice users: TypeToken is similar to Guice's TypeLiteral class, but with one important difference: it supports non-reified types such as T, List<T> or even List<? extends Number>; while TypeLiteral does not. TypeToken is also serializable and offers numerous additional utility methods.

I look forward to giving this a spin next time the need arises.

1 comment:

Unknown said...

I find javaRuntype very handy also.