Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 953
Feuermurmel Avatar asked Nov 24 '22 22:11

Feuermurmel


1 Answers

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.

like image 68
Terafor Avatar answered Nov 26 '22 19:11

Terafor