Triton Man Triton Man - 5 months ago 7
Java Question

How do you get List<Type> with reflection?

I have am getting a method, and checking

method.getParameterTypes()[0]
, which is a
java.util.List
. But I want to figure out what the containing type is, for instance if it's a
java.util.List<String>
I want to figure out that it should hold strings.

How do I do this?

Thanks!

Answer
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.

Comments