Triton Man Triton Man - 1 year ago 69
Java Question

How do you get List<Type> with reflection?

I have am getting a method, and checking

, which is a
. But I want to figure out what the containing type is, for instance if it's a
I want to figure out that it should hold strings.

How do I do this?


Answer Source
Type listType = method.getGenericParameterTypes()[0];
if (listType instanceof ParameterizedType) {
    Type elementType = ((ParameterizedType) listType).getActualTypeArguments()[0];

Note that the element type needn't be an actual Class like String -- it could be a type variable, a wildcarded type, etc.

You can read more about scraping generics info from reflected items here and here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download