How to Cast the Class Object of a Generic Type to

2020-03-24 06:45发布

问题:

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.

回答1:

There are similar questions:

  • Java generics - get class?
  • How to get a class instance of generics type T

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java.