By jj83777
via tutorials.jenkov.com
Published: Sep 02 2008 / 06:10
I have often read in articles and forums that all Java Generics information is erased at compile time so that you cannot access any of that information at runtime. This is not entirely true though. It is possible to access generics information at runtime in a handful of cases. These cases are very useful when implementing frameworks and API's. This text explains the most commonly used cases.
Comments
Ricky Clarkson replied ago:
He missed a bit, kind of. When you subclass a generic class non-generically, as in: class MyList extends ArrayList>, you can see the type parameter via reflection. The interesting part is that this works for anonymous classes also - new ArrayList>(){} - you can grab the type parameter with an incantation I don't recall right now.
Jakob Jenkov replied ago:
Come on, Ricky, give us the code :-) ... the secret spell!
Nice tip! I may try to incorporate it into the text. I'm kinda trying to gather
as much reflection information in one place as possible. All the little secrets I have
learned over the years, but are spread out over notes, blog posts, code samples etc.
E.g. tomorrow I'll be posting on accessing private fields and methods of other classes via reflection...
Voters For This Link (18)
Voters Against This Link (0)