标题: Java 获取方法中的,返回值中 形参类型,及参数中泛型的参数列表
public class TestDemo022 {
private static void test(Map<String,Person> map,List<Integer> list,int id) {
System.out.println("哈哈哈,我在map,list,int中");
}
private static Map<Person,Integer> test2(){
return null;
}
public static void main(String[] args) throws Exception {
Class clazz=TestDemo022.class;
Method method=clazz.getDeclaredMethod("test", Map.class,List.class,int.class);
Type[] types = method.getGenericParameterTypes();
System.out.println("test方法中形参列表的所有形参类型:");
for(Type type:types) {
System.out.println(type);
}
System.out.println("--------------");
for(Type type:types) {
System.out.println("形参类型为:"+type);
if(type instanceof ParameterizedType) {
System.out.println("泛型中的参数列表为:");
Type[] actualTypeArguments = ((ParameterizedType)type).getActualTypeArguments();
for(Type actualType:actualTypeArguments) {
System.out.print(actualType.getTypeName()+" , ");
}
System.out.println();
}
}
System.out.println("----------测试返回值的");
Method method2=clazz.getDeclaredMethod("test2");
Type returnType = method2.getGenericReturnType();
System.out.println("返回值的参数类型:"+returnType);
if(returnType instanceof ParameterizedType)
{
Type[] actualTypeArguments = ((ParameterizedType)returnType).getActualTypeArguments();
for(Type actualType:actualTypeArguments) {
System.out.print(actualType+",");
}
}
}
}