Is it possible to get the type of a generic parameter?
An example:
public final class Voodoo {
public static void chill(List<?> aListWithTypeSpiderMan) {
// Here I'd like to get the Class-Object 'SpiderMan'
Class typeOfTheList = ???;
}
public static void main(String... args) {
chill(new ArrayList<SpiderMan>());
}
}
There is a solution actually, by applying the "anonymous class" trick and the ideas from the Super Type Tokens:
The trick lies in the creation of an anonymous class,
new ArrayList<SpiderMan>() {}
, in the place of the original (simple)new ArrayList<SpiderMan>()
. The use of an anoymous class (if possible) ensures that the compiler retains information about the type argumentSpiderMan
given to the type parameterList<?>
. Voilà !Just for me reading this snippet of code was hard, I just divided it into 2 readable lines :
I wanted to create an instance of the Type parameter without having any parameters to my method :
Actually I got this to work. Consider the following snippet:
I'm using jdk 1.6
This is impossible because generics in Java are only considered at compile time. Thus, the Java generics are just some kind of pre-processor. However you can get the actual class of the members of the list.