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);
}
}
}
}
作者最新文章
漫蛙漫画app下载入口
2026-10-13 13:18
漫蛙漫画免费下载最新版本
2026-10-13 13:18
漫蛙网页版快捷入口
2026-10-13 13:16
漫蛙manwa2官方网页链接下载最新版v3.57
2026-10-13 13:16
漫蛙manwa在线浏览入口
2026-10-13 13:15
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多









































