java再复习——通过反射获取到方法的参数和返回值的泛型类型

我们都知道了可以定义带有泛型参数的方法,以及泛型返回值的方法了,那么泛型在运行的时候已经被擦除了,我们该如何知道这个泛型到底是什么呢?有很多情况需要知道实际泛型是什么,Android数据库框架以及Http框架在解析成json成实体类的时候,必然要知道是哪个类。

获取参数的泛型API方法:

public class GenericParameterizedTypeDemo {

	public static void main(String[] args) throws Exception {
		//通过反射获取到方法
		Method declaredMethod = GenericParameterizedTypeDemo.class.getDeclaredMethod("findStr", int.class,Map.class);
		//获取到方法的参数列表
		Type[] parameterTypes = declaredMethod.getGenericParameterTypes();
		for (Type type : parameterTypes) {
			System.out.println(type);
			//只有带泛型的参数才是这种Type,所以得判断一下
			if(type instanceof ParameterizedType){
				ParameterizedType parameterizedType = (ParameterizedType) type;
				//获取参数的类型
				System.out.println(parameterizedType.getRawType());
				//获取参数的泛型列表
				Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
				for (Type type2 : actualTypeArguments) {
					System.out.println(type2);
				}
			}
		}
	}
	
	public static List findStr(int id,Map map){
		return null;
	}
	
}

一定是getGenericParameterTypes()方法,getParameterTypes得到的参数列表Type对象时不保存泛型类型的。


获取返回值泛型的API方法:

public class GenericParameterizedTypeDemo {

	public static void main(String[] args) throws Exception {
		//通过反射获取到方法
		Method declaredMethod = GenericParameterizedTypeDemo.class.getDeclaredMethod("findStr", int.class,Map.class);
		//获取返回值的类型,此处不是数组,请注意智商,返回值只能是一个
		Type genericReturnType = declaredMethod.getGenericReturnType();
		System.out.println(genericReturnType);
		//获取返回值的泛型参数
		if(genericReturnType instanceof ParameterizedType){
			Type[] actualTypeArguments = ((ParameterizedType)genericReturnType).getActualTypeArguments();
			for (Type type : actualTypeArguments) {
				System.out.println(type);
			}
		}
	}
	
	public static List findStr(int id,Map map){
		return null;
	}
	
}


你可能感兴趣的:(java)