前言
原创文章欢迎转载,请保留出处。
若有任何疑问建议,欢迎回复。
邮箱:Maxwell_nc@163.com
由于不能通过一个变量来获取他的泛型实际参数,我们参考hibernate的源码,通过反射来获得泛型的实际参数。
通过反射获得泛型的实际参数
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class GenericTest {
public static void main(String[] args)throws Exception {
//首先获得传入泛型参数的方法
Method applyMethod = GenericTest.class.getMethod("applyArrayList", ArrayList.class);
//使用getGenericParameterTypes方法,这个方法只有在JDK 1.5以上才能用
Type[] types = applyMethod.getGenericParameterTypes();
//把获得Type数组转成ParameterizedType
ParameterizedType pType = (ParameterizedType)types[0];
//ParameterizedType中的两个方法分别获取原始类型和泛型实际参数
System.out.println(pType.getRawType());
System.out.println(pType.getActualTypeArguments()[0]);
}
public static void applyArrayList(ArrayList<String> arr){}
}