反射获取泛型

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

 

posted on   ~码铃薯~  阅读(168)  评论(0编辑  收藏  举报

编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示