Java reflection: What does my Collection contain?

generics, java, reflection

Solution

Method.getGenericParameterTypes();

returns an array of Types which the parameter accepts. Complexity increases exponentially from there.

In your specific case, this would work:

    Method m = Something.class.getMethod("setCollection", Collection.class);
    Class<?> parameter = (Class<?>) ((ParameterizedType) m.getGenericParameterTypes()[0]).getActualTypeArguments()[0];

But there are a lot of potential gotchas there, depending on how the parameter was declared. If it is a simple as in your example, great. If not, then there are a bunch of types you have to account for, both in the getGenericParameterTypes() method and in the getActualTypeArguments() method. It gets very hairy and ugly very fast.

Problem

I've defined a method in a class: ``` public void setCollection(Collection<MyClass>); ``` and in another class ``` public void setCollection(Collection<OtherClass>); ``` (and really, lots of similar classes) All are in classes with the same superclass, and I have a method in a support-class where I want to call this method and set it with items of the correct class type. Now, I can get that I'm setting a Collection by doing ``` Method setter = ...; Class<?> paramClass = setter.getParameterTypes()[0]; // Is Collection in this case if(paramClass.equals(Collection.class)) { HashSet col = new HashSet(); // fill the set with something setter.invoke(this, col); } ``` But how do I figure out what class the objects in this collection should belong to? Cheers Nik

Original source