反射获取泛型
package com.sinosoft;
import com.sinosoft.lis.bq.PEdorAppBL;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;
//使用反射获取泛型信息
public class Test {
public String test01(Map<String, PEdorAppBL> map,Double dou){
return "yyy";
}
public Map<String, PEdorAppBL> test02(){
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
System.out.println("方法1");
Method method = Test.class.getMethod("test01", Map.class, Double.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("方法2");
Method method2 = Test.class.getMethod("test02", null);
Type genericReturnType = method2.getGenericReturnType();
if(genericReturnType instanceof ParameterizedType){
Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
for(Type actualTypeArgument:actualTypeArguments){
System.out.println(actualTypeArgument);
}
}
}
}
运行结果:
方法1
==========java.util.Map<java.lang.String, com.sinosoft.lis.bq.PEdorAppBL>
class java.lang.String
class com.sinosoft.lis.bq.PEdorAppBL
==========class java.lang.Double
方法2
class java.lang.String
class com.sinosoft.lis.bq.PEdorAppBL
具体代码解释,可以参考这个网址:https://blog.csdn.net/weixin_39452731/article/details/82916840