通过反射获取泛型
通过反射获取泛型
下面是示例代码:
User类
package com.han.reflection;
public class User {
private String id;
private String name;
private int age;
public User() {
}
public User(String id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
测试类
package com.han.reflection;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
/*
通过反射获取泛型
*/
public class Test01 {
public static void test1(Map<String,User> map, List<User> list){
System.out.println("test1");
}
public static Map<String,User> test2(){
System.out.println("test2");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
Method method = Test01.class.getMethod("test1", Map.class, List.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.println("泛型参数化类型:"+genericParameterType);
if(genericParameterType instanceof ParameterizedType){
//真实的参数类型
Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println("真实的参数类型:"+actualTypeArgument);
}
}
}
System.out.println("==========================================");
method = Test01.class.getMethod("test2",null);
Type genericReturnType = method.getGenericReturnType();
System.out.println("泛型返回值类型:"+genericReturnType);
if(genericReturnType instanceof ParameterizedType){
//真实的参数类型
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for (Type actualTypeArgument : actualTypeArguments) {
System.out.println("真实的参数类型:"+actualTypeArgument);
}
}
}
}
输出结果如下:
泛型参数化类型:java.util.Map<java.lang.String, com.han.reflection.User>
真实的参数类型:class java.lang.String
真实的参数类型:class com.han.reflection.User
泛型参数化类型:java.util.List<com.han.reflection.User>
真实的参数类型:class com.han.reflection.User
==========================================
泛型返回值类型:java.util.Map<java.lang.String, com.han.reflection.User>
真实的参数类型:class java.lang.String
真实的参数类型:class com.han.reflection.User