aspose file tools
The moose likes Java in General and the fly likes Generic Collection Type Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Generic Collection Type" Watch "Generic Collection Type" New topic
Author

Generic Collection Type

Dave Radtke
Greenhorn

Joined: Feb 20, 2009
Posts: 2
I'm trying to create a function that can determine the Component Type of any generic collection. I would have though this would be an easy question, but after many hours of searching I haven't found anything.

I have found this works, but only if the collection contains a value, which I cannot rely on.



Thanks
Dave
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32833
    
    4
Because of erasure that information is no longer available at runtime.
That sort of question comes up several times a year; if you search you will find suggestions, but there is no straightforward way to retrieve "<T>" and workout what "T" stands for.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16813
    
  19

I have found this works, but only if the collection contains a value, which I cannot rely on.


Also, it may not be reliable... for example, if someone calls your method with a Collection<Animal> object, that contains Dogs, Cats, Horses, Cows, etc.... With your solution, you can mistakenly get the first element, which may be a Cow, and assume that it is a Collection<Cow> object.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Dave Radtke
Greenhorn

Joined: Feb 20, 2009
Posts: 2
Campbell Ritchie wrote:Because of erasure that information is no longer available at runtime.
That sort of question comes up several times a year; if you search you will find suggestions, but there is no straightforward way to retrieve "<T>" and workout what "T" stands for.


Well, I feel better that at least I'm not just missing the obvious.

I have been searching, and the closes I have found was this Getting-generic-type-Collection but that sample appears to only work if you have the collection as a declared field within another object. I already have a method to workout it out from a PropertyDescriptor. But in this situation all I have is the collection itself.


What search terms should I be using?



 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generic Collection Type
 
Similar Threads
generics code mixed with legacy collection
get Property-Field-Name via Reflection
Creating Generic Method !
it cannot be parameterized with arguments <? extends E>
Ultimate generics Q