tags:

views:

250

answers:

2

How can I access Class object for Generics?

Currently, I am doing it this way:

List<String> list= new ArrayList<String>();
list.getClass();

Is this OK? Or, what should be the way?

+7  A: 

That will return the same as ArrayList.class. Java generics erase the generic type at runtime; in other words, from "list" you'll never know the element type is String. There's a great FAQ on this at

http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html

João da Silva
+3  A: 

It is true that erasure makes it impossible to get the generic type info of a given object, since the generics is only held in the structure of the source code. However, this does not mean it's impossible to get generic type parameters and in many important cases (e.g. building interfaces to a given class/method) you are able to do this. If you get hold of a class' elements via reflection, you can get generic information about the declared types used.

For example, get hold of a java.lang.reflect.Method via reflection, and call e.g. getGenericReturnType() on it. This will return an instance of java.lang.reflect.Type, which can be simply a Class but could also be an instance of ParameterizedType or even WildcardType where appropriate. Both of these latter cases allow you to see the declared generic types. I am not aware of any particularly elegant way to handle this other than instanceof checks, but the information is there if you need it.

This can give information on the generics types of fields, of method parameters and return types, and of the class itself (both its own generic parameters and those of its superclass and implemented interfaces). This can be very useful if you need to do type-safe argument checking for generic methods in a reflective context.

Andrzej Doyle