java如何使用ParameterizedType实现泛型
作者:小月亮
时间:2023-05-02
浏览:1
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);
}
}
}
}
作者最新文章
漫蛙漫画入口及官网访问指南
2026-11-21 16:53
AI桌面浏览器AI助理预测功能怎么用 提问方法是什么
2026-11-20 13:46
樱花动漫账户注册网址与最新版网页端登陆入口
2026-11-16 18:58
会声会影如何给视频打马赛克 功能滤镜与局部遮挡操作
2026-11-11 14:34
Win10开机密码怎么取消 系统账户设置与删除密码方法
2026-11-11 09:28
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































