How do you get List with reflection?

2020-05-27 02:29发布

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!

3条回答
smile是对你的礼貌
2楼-- · 2020-05-27 03:01
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.

查看更多
等我变得足够好
3楼-- · 2020-05-27 03:01

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.

查看更多
太酷不给撩
4楼-- · 2020-05-27 03:03

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]
查看更多
登录 后发表回答