Pass the class object instead and it's easy. The idea here is that since you can't extract the type parameter from the object, you have to do it the other way around: start with the class and then manipulate the object to match the type parameter.
Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow "a type or method to operate on objects of various types while providing compile-time type safety".
To construct an instance of a generic typeThe MakeGenericType method requires a generic type definition. Construct an array of type arguments to substitute for the type parameters. The array must contain the correct number of Type objects, in the same order as they appear in the type parameter list.
A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.
how about
(Class<List<Object>>)(Class<?>)List.class
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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With