得到当前类的泛型类型

来源:互联网 发布:云计算技术与应用就业 编辑:程序博客网 时间:2024/06/05 16:31
package snippet;import java.lang.reflect.Method;import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;/** * 得到当前类的泛型类型 * @author jx * * @param <PPrint> */public class Test<PPrint> {public Test<PPrint> getType() {return null;}/** * 通过方法的返回值,获得当前类的泛型 * 获得当前类的泛型,首先要创建一个返回值为当前类的方法,用反射来获取这个返回值的泛型类型,即当前类的泛型类型 * @param method  * @return */public static String getClassGenericType(Method method) {// 得到方法的返回值类型Type returnType = method.getGenericReturnType();// 返回类型// 如果是参数化类型,如 Collection<String>if (returnType instanceof ParameterizedType) {// 得到返回值的泛型类型列表Type[] types = ((ParameterizedType) returnType).getActualTypeArguments();// 泛型类型列表return types[0].toString() != null ? types[0].toString() : "";}return "";}/** * @param args */public static void main(String[] args) throws Exception {Method method = Test.class.getMethod("getType", null);System.out.println(Test.getClassGenericType(method));}}

原创粉丝点击