Triton Man Triton Man - 8 months ago 21
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?


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.