How to get Class for generic type?
A class object is not specific to the particular class that is satisfying its type parameter:
assert (new ArrayList<String>()).getClass() == (new ArrayList<Integer>()).getClass();
It's the exact same object regardless of how it's typed.
You can not, since generic information is not present during runtime, due to type erasure.
Your code can be written like:
List<String> list = new ArrayList<String>();
Class c1 = list.getClass();
Class c2 = Class.forName("java.util.ArrayList");
System.out.println(c1 == c2); // true
Class
does not represent general types. The appropriate type to use is java.lang.reflect.Type
, in particular ParameterizedType
. You can get these objects via reflection or make your own.
(Note, generics is a static-typing feature so isn't really appropriate for runtime objects. Static typing information happens to be kept in class files and exposed through the reflection API on reflective objects.)