I have a generic interface, lets call it GenericInterface<T>
. I need to pass the class object of that interface to a method that expects (specified through another type parameter) a specific instance of that type. Let's assume I want to call java.util.Collections.checkedList()
:
List<GenericInterface<Integer>> list = Collections.checkedList(
new ArrayList<GenericInterface<Integer>>(),
GenericInterface.class);
This does not work because Class<GenericInterface>
cannot be implicitly casted to Class<GenericInterface<Integer>>
, what is the most type safe way to do that? The best I could come up is this:
List<GenericInterface<Integer>> list = Collections.checkedList(
new ArrayList<GenericInterface<Integer>>(),
(Class<GenericInterface<Integer>>) (Class<?>) GenericInterface.class);
It works but won't protect me from e.g. changing the list's type to List<SomeOtherInterface>
without also replacing the class object parameter with SomeOtherInterface.class
.
There are similar questions:
The short answer is, that there is no way to find out the runtime type of generic type parameters in Java.
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