This post originated from an RSS feed registered with Agile Buzz
by Joe Walnes.
Original Post: Accessing generic type information at runtime
Feed Title: Joe's New Jelly
Feed URL: http://joe.truemesh.com/blog/index.rdf
Feed Description: The musings of a ThoughtWorker obsessed with Agile, XP, maintainability, Java, .NET, Ruby and OpenSource. Mmm'kay?
A common misconception about generics in Java 5 is that you can't access them at runtime.
What you can't find out at runtime is which generic type is associated with an instance of an object. However you can use reflection to look at which types have been staticly associated with a member of a class.
public class GenericsTest extends TestCase {
class Thing {
public Map<String,Integer> stuff;
}
public void test() throws Exception {
Field field = Thing.class.getField("stuff");
ParameterizedType type = (ParameterizedType) field.getGenericType();
assertEquals(Map.class, type.getRawType());
assertEquals(String.class, type.getActualTypeArguments()[0]);
assertEquals(Integer.class, type.getActualTypeArguments()[1]);
}
}
Just wanted to clear that up.
(This is something that I'll probably exploit in XStream for J5 users to further simplify the XML.)