How to Cast the Class Object of a Generic Type to a Specific Instance of that Type

无人久伴 提交于 2019-12-19 08:30:42

问题


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.



来源:https://stackoverflow.com/questions/16735060/how-to-cast-the-class-object-of-a-generic-type-to-a-specific-instance-of-that-ty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!