java 泛型 深入(三)

2014-11-24 09:12:31 · 作者: · 浏览: 8
lass; //取得 Class
Method method = clazz.getDeclaredMethod("applyCollection", Collection.class); //取得方法
Type[] type = method.getGenericParameterTypes(); //取得泛型类型参数集
ParameterizedType ptype = (ParameterizedType)type[0];//将其转成参数化类型,因为在方法中泛型是参数,且Number是第一个类型参数
type = ptype.getActualTypeArguments(); //取得参数的实际类型
System.out.println(type[0]); //取出第一个元素
} catch (Exception e) {
e.printStackTrace();
}
}

//声明一个空的方法,并将泛型用做为方法的参数类型
public void applyCollection(Collection collection){

}
}

后台打印输出的结果:


class java.lang.Number


通过字段变量,反射获得泛型的实际类型参数:

package test;www.2cto.com

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map;

/**
* -----------------------------------------
* @描述 测试类
* @作者 fancy
* @邮箱 fancydeepin@yeah.net
* @日期 2012-8-26


* -----------------------------------------
*/
public class Test {

private Map collection;

public static void main(String[] args){

try {

Class< > clazz = Test.class; //取得 Class
Field field = clazz.getDeclaredField("collection"); //取得字段变量
Type type = field.getGenericType(); //取得泛型的类型
ParameterizedType ptype = (ParameterizedType)type; //转成参数化类型
System.out.println(ptype.getActualTypeArguments()[0]); //取出第一个参数的实际类型
System.out.println(ptype.getActualTypeArguments()[1]); //取出第二个参数的实际类型

} catch (Exception e) {
e.printStackTrace();
}
}

}

后台打印输出的结果:


class java.lang.String
class java.lang.Number