----------------------
ASP.Net+Android+IOS开发、
.Net培训、期待与您交流! ----------------------
HashSet<Integer> set = new HashSet<Integer>();
可不可以通过变量set得到集合的泛型类型Integer?不可以。
因为集合没有提供这样的方法,而如果使用反射的话,在编译器编译源文件后会去掉泛型,反射得到的字节码中不会保留泛型类型。
那么如何得到泛型类型呢?
我们可以将其作为一个方法的形参,使用该方法来得到。
Method类提供了一个方法:getGenericParameterTypes。这个方法按照声明顺序返回 Type 对象的数组,这些对象描述了此 Method 对象所表示的方法的形参类型的。
ParameterizedType 表示参数化类型,如 Collection<String>。其方法getActualTypeArguments返回表示此类型实际类型参数的Type对象的数组。
public class ReflectGeneric {
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
//得到print方法Method对象
Method method = ReflectGeneric.class.getMethod("print", HashSet.class);
//获取该方法所有形参的类型,并带有泛型
Type[] types = method.getGenericParameterTypes();
//使用ParameterizedType得到参数类型
ParameterizedType pType = (ParameterizedType)types[0];
//得到此类型实际类型参数
System.out.println(pType.getActualTypeArguments()[0]);
//得到原始类型
System.out.println(pType.getRawType());
}
public static void print(HashSet<Integer> set){}
----------------------
ASP.Net+Android+IOS开发、
.Net培训、期待与您交流! ----------------------详细请查看:
http://edu.csdn.net