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
.