java如何使用ParameterizedType实现泛型
作者:小月亮
时间:2023-05-02
来源:正软商城
浏览:0
1、过程(1)测试属性类型(2)打印type与generictype的区别(3)测试参数类型(4)测试返回值类型2、实例publicclassClient{privateMapobjectMap;publicvoidtest(Mapmap,Stringstring){}publicMaptest(){returnnull;}/***测试属性类型**@throwsNoSuchFieldException*/@TestpublicvoidtestFieldType()throwsNoSuchFieldExce
本文目录
1、过程
(1)测试属性类型
(2)打印type与generic type的区别
(3)测试参数类型
(4)测试返回值类型
2、实例
public class Client {
private Map objectMap;
public void test(Map map, String string) {
}
public Map test() {
return null;
}
/**
* 测试属性类型
*
* @throws NoSuchFieldException
*/
@Test
public void testFieldType() throws NoSuchFieldException {
Field field = Client.class.getDeclaredField("objectMap");
Type gType = field.getGenericType();
// 打印type与generic type的区别
System.out.println(field.getType());
System.out.println(gType);
System.out.println("**************");
if (gType instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) gType;
Type[] types = pType.getActualTypeArguments();
for (Type type : types) {
System.out.println(type.toString());
}
}
}
/**
* 测试参数类型
*
* @throws NoSuchMethodException
*/
@Test
public void testParamType() throws NoSuchMethodException {
Method testMethod = Client.class.getMethod("test", Map.class, String.class);
Type[] parameterTypes = testMethod.getGenericParameterTypes();
for (Type type : parameterTypes) {
System.out.println("type -> " + type);
if (type instanceof ParameterizedType) {
Type[] actualTypes = ((ParameterizedType) type).getActualTypeArguments();
for (Type actualType : actualTypes) {
System.out.println("\tactual type -> " + actualType);
}
}
}
}
/**
* 测试返回值类型
*
* @throws NoSuchMethodException
*/
@Test
public void testReturnType() throws NoSuchMethodException {
Method testMethod = Client.class.getMethod("test");
Type returnType = testMethod.getGenericReturnType();
System.out.println("return type -> " + returnType);
if (returnType instanceof ParameterizedType) {
Type[] actualTypes = ((ParameterizedType) returnType).getActualTypeArguments();
for (Type actualType : actualTypes) {
System.out.println("\tactual type -> " + actualType);
}
}
}
}
作者最新文章
wps如何生成目录自动生成目录
2026-11-05 11:16
二狗PPT怎么用Word文档生成PPT
2026-11-03 14:55
office打开弹出另存为 修复保存设置
2026-11-03 10:08
火山引擎EMRAI助手导出诊断结果方法
2026-11-01 19:35
navicat连接mysql数据库 配置测试方法
2026-10-26 10:02
热门文章
更多
精品专题
更多
Mac软件
更多
火山引擎 网页版
Windows/ macOS/ Linux
火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。
















