How do you get List with reflection?

2020-05-27 02:48发布

问题:

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!

回答1:

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.



回答2:

It's simple : you can't. At compile time, Java erases generic types (see Type erasure).

You can see here and here for more information about GetGenericType (which I didn't know about, honestly), but it seems rather limited.



回答3:

I had the same issue, and I did as below

in here : your class is initialize as clazz (eg - Company.Class) and your Collection as

List<Employees> companyEmployee

String collectionType- List

String collectionContent - Employee


Method[] methodList = clazz.getDeclaredMethods();
Method classMethod = methodList[0];

String[] collection= classMethod.getReturnType().toString().split("\\.");

String collectionType = collection[collection.length - 1]

String collectionContent = classMethod.getGenericReturnType().getTypeName().split("<")[1].split(">")[0]