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>());
}
}
Nope, that is not possible. Due to downwards compatibility issues, Java's generics are based on type erasure, i.a. at runtime, all you have is a non-generic
List
object. There is some information about type parameters at runtime, but it resides in class definitions (i.e. you can ask "what generic type does this field's definition use?"), not in object instances.You cannot get a generic parameter from a variable. But you can from a method or field declaration:
No it isn't possible.
You can get a generic type of a field given a class is the only exception to that rule and even that's a bit of a hack.
See Knowing type of generic in Java for an example of that.
You can get the type of a generic parameter with reflection like in this example that I found here:
I've coded this for methods which expect to accept or return
Iterable<?...>
. Here is the code:The quick answer the the Question is no you can't, because of Java generic type erasure.
The longer answer would be that if you have created your list like this:
Then in this case the generic type is preserved in the generic superclass of the new anonymous class above.
Not that I recommend doing this with lists, but it is a listener implementation:
And since extrapolating the generic types of super classes and super interfaces change between JVMs, the generic solution is not as straight forward as some answers might suggest.
Here is now I did it.