Java中如何获得集合变量的集合中的类型参数

 

 

 

例如:Vector<Data> v = new Vector<Data>(); 这个里面我们是无法通过变量v而得到Vector中参数的类型,因为Vector<Data>在编译后字节码中去掉了类型,也就是说Vector<Data>和和Vector<T>的字节码是一样的,所以不能取得Vector中的参数类型,那我们可以通过把v作为一个参数传入一个方法中来获得Vector中的参数类型,因为通过反射获得的Method中有能够获得参数化的类型的方法,如下:

public class GenericTest {
	public static void main(String[] args) throws Exception {
		Method method = GenericTest.class.getMethod("getGenericType", Vector.class);
		Type[] type = method.getGenericParameterTypes();
		ParameterizedType pType = (ParameterizedType)type[0];
		System.out.println(pType.getRawType());
		System.out.println(pType.getActualTypeArguments()[0]);
	}
	
	public static void getGenericType(Vector<Data> v){
		
	}
}


打印结果:

class java.util.Vector
interface javax.xml.crypto.Data


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章