Win a copy of Murach's MySQL this week in the JDBC and Relational Databases forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Getting the generic type of a Collection

 
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm using reflection to inspect a collection and want to get the Class of the objects that can be put inside of it. Is this seriously the only way to get the class:

(Class)((ParameterizedType)field.getGenericType()).getActualTypeArguments()[0]
 
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Result is Field 0 java.util.List<java.lang.Number>
 
todd runstein
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks,

I looked at using Field.getGenericType().toString(), but because I need the java.lang.Number class, that didn't get me very far. I couldn't see a convenient (or reliable) way of getting the correct class from the getGenericType().toString() output.

Todd
 
Sheriff
Posts: 22778
130
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
getGenericType returns a Type, but that's just an interface. It can be any class, as long as it implements Type.

Check if it also implements ParameterizedType. If so, the information is in the return value of getActualTypeArguments somewhere. At least, that's what a bit of testing has shown me.

You'll have to investigate the contents a bit more, using reflection for checking the implementing interfaces and the super classes.
[ April 08, 2008: Message edited by: Rob Prime ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic