Class object of generic class (java)

JavaGenerics

Java Problem Overview


is there a way in java to get an instance of something like Class<List<Object>> ?

Java Solutions


Solution 1 - Java

how about

(Class<List<Object>>)(Class<?>)List.class

Solution 2 - Java

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);

Solution 3 - Java

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.

Solution 4 - Java

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.

Solution 5 - Java

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.

Solution 6 - Java

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.

Solution 7 - Java

List.class

the specific type of generics is "erased" at compile time.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmisko herkoView Question on Stackoverflow
Solution 1 - JavanewacctView Answer on Stackoverflow
Solution 2 - JavaArmhartView Answer on Stackoverflow
Solution 3 - JavaYishaiView Answer on Stackoverflow
Solution 4 - JavaTom Hawtin - tacklineView Answer on Stackoverflow
Solution 5 - JavaLorcan O'NeillView Answer on Stackoverflow
Solution 6 - JavajwoolardView Answer on Stackoverflow
Solution 7 - JavaJason SView Answer on Stackoverflow