Accessing generic type information at runtime
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 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.)
Joe,
How do you plan to support J5 users while still supporting the rest of the community? This is something I want to do with WebWork (support Annotations and Generics, but not require it). Any plans? Drop me an email sometime and let me know.
Patrick
ParameterizedType type = (ParameterizedType) field.getGenericType();
assertEquals(Map.class, type.getRawType());
assertEquals(String.class, type.getActualTypeArguments()[0]);
assertEquals(Integer.class, type.getActualTypeArguments()[1]);
}
http://www.usdebtconsolidation.net