通过反射获取变量泛型参数化的类型

package com.franky.generic;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @描述   通过反射获取泛型的参数化类型
 * @作者 franky
 * @日期 2015-1-1 下午4:55:40
 * 
 */
public class GetGenericPrams {

	/**
	 * @param args
	 * @throws Exception 
	 * @throws NoSuchMethodException 
	 */
	public static void main(String[] args) throws NoSuchMethodException, Exception {
		//直接通过参数化泛型的变量是无法获取泛型的参数化类型的,只能通过使用该变量的方法获取
		ArrayList<Date> list = new ArrayList<Date>();
		Type[] types = GetGenericPrams.class.getMethod("genericMethod", ArrayList.class).getGenericParameterTypes();
		ParameterizedType pType  =  (ParameterizedType) types[0];
		//得到泛型的实际的参数化类型(列表,可能是多个泛型参数,如Map) class java.util.Date  
		Type actType = pType.getActualTypeArguments()[0];
		//得到方法参数列表的参数类型class java.util.ArrayList
		Type rawType = pType.getRawType();
		//如果类型为某个类的内部成员,那么返回所在的类的类型,否者返回 null
		Type ownerType = pType.getOwnerType();
		
		System.out.println(actType);//class java.util.Date  
		System.out.println(rawType);//class java.util.ArrayList
		System.out.println(ownerType);//null
		
		
	}
	
	public static void genericMethod(ArrayList<Date> list){
		
	}

}

猜你喜欢

转载自blog.csdn.net/franky814/article/details/42320117