is there a way in java to get an instance of something like Class<List<Object>> ?
7 Answers
how about
(Class<List<Object>>)(Class<?>)List.class
7 Comments
(Class<?>) really needed ? In my tests it seems like (Class<List<Object>>)List.class is enough.java.awt.List instead of the interface java.util.List). Check your imports.public final class ClassUtil {
@SuppressWarnings("unchecked")
public static <T> Class<T> castClass(Class<?> aClass) {
return (Class<T>)aClass;
}
}
Now you call:
Class<List<Object>> clazz = ClassUtil.<List<Object>>castClass(List.class);
3 Comments
(Class<List<Object>>)(Class<?>)List.class but if you need several class objects, you will only have one unchecked cast inside the ClassUtil.super of T. public static <T> Class<T> castClass(Class<? super T> aClass)Because of type erasure, at the Class level, all List interfaces are the same. They are only different at compile time. So you can have Class<List> as a type, where List.class is of that type, but you can't get more specific than that because they aren't seperate classes, just type declarations that are erased by the compiler into explicit casts.
Comments
As mentioned in other answers, Class represents an erased type. To represent something like ArrayList<Object>, you want a Type. An easy way of getting that is:
new ArrayList<Object>() {}.getClass().getGenericSuperclass()
The generic type APIs introduced in 1.5 are relatively easy to find your way around.
5 Comments
You can get a class object for the List type using:
Class.forName("java.util.List")
or
List.class
But because java generics are implemented using erasures you cannot get a specialised object for each specific class.