java 反射取得方法入参类型的泛形

时间:2021-09-19 19:41:17
package TestReflectClass;

import java.util.List;

/**
* Created by wangyang on 2016/12/16.
*/
public class Person {
public void get(List<A> list){ }
}
class A{}
package TestReflectClass;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List; /**
* Created by wangyang on 2016/12/16.
*/
public class TestReflect {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException {
Class<?> aClass = Class.forName("TestReflectClass.Person");
Method method = aClass.getMethod("get", List.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();
for(Type genericParameterType : genericParameterTypes){
if(genericParameterType instanceof ParameterizedType){
ParameterizedType aType = (ParameterizedType) genericParameterType;
Type[] parameterArgTypes = aType.getActualTypeArguments();
for(Type parameterArgType : parameterArgTypes){
Class parameterArgClass = (Class) parameterArgType;
System.out.println("parameterArgClass = " + parameterArgClass);
}
}
}
}
}