Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class object of generic class (java)

Tags:

java

generics

People also ask

How do you find the class object of a generic type?

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.

What are generic objects in Java?

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".

Can you create an object of generic type?

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.

What is generic classes in Java?

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.