Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a class reference to parameterized type

Is there any chance to assign to class reference the parameterized type eg.

    Class<Set>  c1= Set.class;   //OK
    Class<Set<Integer>> c2 = Set<Integer>.class; //Makes error
like image 955
Andrzej Marciniak Avatar asked Feb 24 '15 11:02

Andrzej Marciniak


People also ask

How do I get a class instance of generic type T?

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.

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. Show activity on this post. Show activity on this post.

What is a parameterized class?

A parameterized class is a generic or skeleton class, which has formal parameters that will be replaced by one or more class-names or interface-names. When it is expanded by substituting specific class-names or interface-names as actual parameters, a class is created that functions as a non-parameterized class.


1 Answers

Using .class literal with a class name, or invoking getClass() method on an object returns the Class instance, and for any class there is one and only one Class instance associated with it.

Same holds true for a generic type. A class List<T> has only a single class instance, which is List.class. There won't be different class types for different type parameters. This is analogous to how C++ implements generics, where each generic type instantiation will have a separate Class instance. So in Java, you can't do Set<Integer>.class. Java doesn't allow that because it doesn't make sense, and might give wrong intentions about number of Class instances.

However, if you want a Class<Set<Integer>>, you can achieve that will a bit of type casting (which will be safe), as shown below:

Class<Set<Integer>> clazz = (Class<Set<Integer>>)(Class<?>) Set.class;

This will work perfectly fine.

like image 67
Rohit Jain Avatar answered Sep 29 '22 13:09

Rohit Jain