• Post Reply Bookmark Topic Watch Topic
  • New Topic

Getting the generic type of a Collection  RSS feed

 
todd runstein
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • 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]
 
Ashok Kumar Babu
Ranch Hand
Posts: 129
  • Mark post as helpful
  • send pies
  • 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
  • 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
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • 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 ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!