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