Link Details

Link 109436 thumbnail
User 131196 avatar

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.
  • 18
  • 0
  • 1631
  • 457

Comments

Add your comment
User 179375 avatar

Ricky Clarkson replied ago:

0 votes Vote down Vote up Reply

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.

User 131196 avatar

Jakob Jenkov replied ago:

0 votes Vote down Vote up Reply

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...

Add your comment


Html tags not supported. Reply is editable for 5 minutes. Use [code lang="java|ruby|sql|css|xml"][/code] to post code snippets.