ParameterizedType 一种参数化类型,比如Collection< String >
GenericArrayType 一种元素类型是参数化类型或者类型变量的数组类型
TypeVariable 是各种类型变量的公共父接口
WildcardType 代表一种通配符类型表达式
获取参数的类型
Class clz = Class.forName("com.hz.Person");
Method printCollection = clz.getDeclaredMethod("printCollection", List.class, Map.class);
Type[] genericParameterTypes = printCollection.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.printf("=================== %s ===================\n", genericParameterType);
if (genericParameterType instanceof ParameterizedType){
//获得Map和List中的泛型类型
Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument.getTypeName());
}
}
}
运行结果:
=================== java.util.List<java.lang.Integer> ===================
java.lang.Integer
=================== java.util.Map<java.lang.Integer, java.lang.String> ================
java.lang.Integer
java.lang.String
获取返回值的类型
Class clz = Class.forName("com.hz.Person");
Method printCollection = clz.getDeclaredMethod("printCollection", List.class, Map.class);
Type genericReturnType = printCollection.getGenericReturnType();
System.out.printf("=============== %s ================\n", genericReturnType);
if (genericReturnType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println(actualTypeArgument);
}
}
运行结果:
=============== java.util.List<java.lang.String> ================
class java.lang.String
原文:https://www.cnblogs.com/icefoxhz/p/13680436.html