Search code examples
javaoopreflectionintrospection

Given a Collection get the type of the items (Java)


I need to get the type of the item of a collection. For retrieving the class of a single instance I use the following code:

classUnderTest.getName()

But, how can I retrieve the class of the items of the following collection?

Collection collection = (Collection) getCollection.invoke(instance1);

Solution

  • You cannot get/infer the generic type of the Collection at runtime due to Type Erasure. Generics are there for compile time safety, the type information is erased during runtime.

    During runtime the instances are Object for collection and it does not care about the actual type on runtime.