如何将通用类型的类对象转换为该类型的特定实例

如何将通用类型的类对象转换为该类型的特定实例

问题描述:

我有一个通用接口,让它调用 GenericInterface< T> 。我需要将该接口的类对象传递给期望(通过另一个类型参数指定)该类型的特定实例的方法。让我们假设我想调用 java.util.Collections.checkedList()

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);

这不起作用,因为 Class< GenericInterface> 不能隐式转换为 Class< GenericInterface< Integer>> ,最类型安全的方法是什么?我可以想到的最好的是:

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);

它可以工作,但不会保护我。将列表的类型更改为 List< SomeOtherInterface> ,而不用类别对象参数替换 SomeOtherInterface.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.

有类似的问题:

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

简单的答案是,没有办法找出运行时类型
的泛型类型参数Java。

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