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)); } }
得到当前类的泛型类型
最新推荐文章于 2024-01-04 14:55:37 发布