is there a way in java to get an instance of something like Class<List<Object>>
?
Asked
Active
Viewed 5.7k times
7 Answers
36
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);

Armhart
- 361
- 3
- 2
-
3Not a bad idea. This is basically the same as doing `(Class
- >)(Class>)List.class` but if you need several class objects, you will only have one unchecked cast inside the ClassUtil.
-
-
1To provide some type safety, you could require the parameter to be `super` of T. `public static
Class – Invitor Jan 04 '22 at 21:17castClass(Class super T> aClass)`
10
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.

configurator
- 40,828
- 14
- 81
- 115

Yishai
- 90,445
- 31
- 189
- 263
6
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.

Tom Hawtin - tackline
- 145,806
- 30
- 211
- 305
-
-
2Not only creating a new object, a new class (in this case an anonymous inner class). But that example should be new ArrayList, no? Making an anonymous list would require you to implement all the methods. – Yishai Jul 03 '09 at 13:49
-
Yishai: Erm yes. And it's getGenericSuperclass not getGenericSupertype. And then there's the issue of implementing multiple interfaces. – Tom Hawtin - tackline Jul 03 '09 at 15:10
-
Jason S: One object who cares? There's ways of doing it without the new, but you are using plenty of memory for code. – Tom Hawtin - tackline Jul 03 '09 at 15:11
-
2
You could use Jackson's ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
CollectionType listType = objectMapper.getTypeFactory().constructCollectionType(List.class, ElementClass.class)
No unchecked warnings, no empty List instances floating around.

Lorcan O'Neill
- 3,303
- 1
- 25
- 24
>)List.class` is enough.
– alarive Jan 20 '15 at 10:16`. A cast from `Class
– newacct Jan 20 '15 at 10:20` to `Class
>` was illegal (because no type could possibly be a subtype of both) the last time I checked