I’d like to get the generic type of a collection, using reflection, at runtime.
Code (JAVA):
Field collectionObject = object.getClass().getDeclaredField(
collectionField.getName());
//here I compare to see if a collection
if (Collection.class.isAssignableFrom(collectionObject.getType())) {
// here I have to use the generic type of the collection
// to see if it's from a specific type - in this case Persistable
if (Persistable.class.isAssignableFrom(GENERIC_TYPE_COLLECTION.class)) {
}
}
Is there a way of getting the generic type of the collection in java at runtime? In my case I need the .class of the collection’s generic type.
Thanks in advance!
Type erasure means that information about the generic type of an object simply isn’t present at execution time.
(The link is to the relevant section of Angelika Langer’s Java Generics FAQ which should answer virtually every question you could possibly ask about Java generics 🙂
However, you’re not really interested in the type of an object – you’re interested in the type of a field. I misread the question, and although the answer has been accepted I hope to make amends by fixing it now 🙂
If the field doesn’t use a type parameter itself, it can be done. For example:
If the field were in a class
Twith the field beingList<T>then you’d have to know the type argument for the instance in order to know the type argument for the collection.Translating this into your required code is somewhat tricky though – you really need to know the type argument at the point of the collection class. For instance, if someone declared:
and then had a field of type
StringCollection, that field itself wouldn’t have any type arguments. You’d then need to checkgetGenericSuperTypeandgetGenericInterfacesrecursively until you found what you wanted.It’s really not going to be easy to do that, even though it’s possible. If I were you I’d try to change your design so that you don’t need this.