十五、反射获取泛型信息
程序员文章站
2024-03-14 18:18:40
...
1、代码
/**
* @Description 反射获取泛型
* @Author Administrator
* @Date 2020/12/2 13:23
*/
public class Test11 {
public void test01(Map<String, User> map, List<User> list){
System.out.println("test01");
}
public Map<String, User> test02(){
System.out.println("test02");
return null;
}
public static void main(String[] args) throws Exception {
Class c1 = Test11.class;
/**
* 1、参数为泛型
*/
Method method = c1.getDeclaredMethod("test01", Map.class, List.class);
Type[] parameterTypes = method.getGenericParameterTypes();
for (Type type : parameterTypes) {
System.out.println("参数类型#" + type);
if(type instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println("\t" + actualTypeArgument);
}
}
}
/**
* 2、返回值为泛型
*/
System.out.println("=======================================");
method = c1.getDeclaredMethod("test02",null);
Type returnType = method.getGenericReturnType();
System.out.println("返回值类型#" + returnType);
if(returnType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) returnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println("\t" + actualTypeArgument);
}
}
}
}
2、结果
参数类型#java.util.Map<java.lang.String, com.hejin.reflection.User>
class java.lang.String
class com.hejin.reflection.User
参数类型#java.util.List<com.hejin.reflection.User>
class com.hejin.reflection.User
=======================================
返回值类型#java.util.Map<java.lang.String, com.hejin.reflection.User>
class java.lang.String
class com.hejin.reflection.User
Process finished with exit code 0
上一篇: java教程——泛型(一)