使用反射获取泛型信息
程序员文章站
2024-03-14 18:10:22
...
反射操作泛型
小案例测试
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 Demo1 {
public void test1(Map<String, 注解和反射.反射.反射概述.Demo1.User> map, List<注解和反射.反射.反射概述.Demo1.User> list) {
System.out.println ("test1");
}
public Map<String, 注解和反射.反射.反射概述.Demo1.User> test2() {
System.out.println ("test2");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
Method method = Demo1.class.getMethod ("test1", Map.class, List.class);
Type[] geths = method.getGenericParameterTypes ();
for (Type gethd : geths) {
System.out.println ("#" + gethd);
if (gethd instanceof ParameterizedType) {
Type[] act = ((ParameterizedType) gethd).getActualTypeArguments ();
for (Type ctt : act) {
System.out.println (ctt);
}
}
}
method = Demo1.class.getMethod ("test2", null);
Type get = method.getGenericReturnType ();
if (get instanceof ParameterizedType) {
Type[] act = ((ParameterizedType) get).getActualTypeArguments ();
for (Type ctt : act) {
System.out.println (ctt);
}
}
}
}